#https://github.com/kairess/socket-chat
#(anaconda) activate pythonProject. cd 파일경로. python server/client.py
<client.py>
import socket
import select
import sys
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8000))
name = None
while True:
read, write, fail = select.select((s,),(),(),1)
if msvcrt.kbhit(): read.append(sys.stdin)
for desc in read:
if desc == s:
data = s.recv(4096)
print(data.decode())
if name is None:
name = data.decode()
s.send(f'{name} is connected!'.encode())
else:
msg = desc.readline()
msg = msg.replace('\n', '')
s.send(f'{name} {msg}'.encode())
v = open('주소/save.txt')
save = v.readlines()
for line in save:
line = line.strip()
v.close()
v2 = open('주소/save2.txt')
num = v2.readline()
v2.close()
num = int(num)
save.append(msg)
num += 1
v = open('주소/save.txt', 'w')
for i in range(num):
v.write(save[i])
v.write('\n')
v.close()
v2 = open('주소/save2.txt', 'w')
v2.write(str(num))
v2.close()
#save.txt: 채팅 메세지 저장, save2.txt: num 값 저장(초기 값: 0)
<server.py>
from twisted.internet import protocol, reactor
import names
COLORS = [
'\033[31m', # RED
'\033[32m', # GREEN
'\033[33m', # YELLOW
'\033[34m', # BLUE
'\033[35m', # MAGENTA
'\033[36m', # CYAN
'\033[37m', # WHITE
'\033[4m', # UNDERLINE
]
transports = set()
users = set()
class Chat(protocol.Protocol):
def connectionMade(self):
name = names.get_first_name()
color = COLORS[len(users) % len(COLORS)]
users.add(name)
transports.add(self.transport)
self.transport.write(f'{name}'.encode())
def dataReceived(self, data):
for t in transports:
if self.transport is not t:
t.write(data)
class ChatFactory(protocol.Factory):
def buildProtocol(self, addr):
return Chat()
print('Server started!')
reactor.listenTCP(8000, ChatFactory())
reactor.run()
top of page
기능을 테스트하려면 라이브 사이트로 이동하세요.
2022.8.20.
2022.8.20.
댓글 0개
좋아요
댓글(0)
bottom of page