#服务器端
import socket import threading #创建一个TCP端 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #接受来自本地,4444端口的数据 sock.bind(('localhost', 4444)) #最大接受参数 sock.listen(5) print('Server', socket.gethostbyname('localhost'), 'listening ...') #创建一个空字典和一个空列表 mydict = dict() mylist = list() # 把whatToSay传给除了exceptNum的所有人 def tellOthers(exceptNum, whatToSay): for c in mylist:#遍历空字典 if c.fileno() != exceptNum: try: c.send(whatToSay.encode())#向tcp发送数据并编码为当前 except: pass def subThreadIn(myconnection, connNumber): nickname = myconnection.recv(1024).decode()#读取网络数据并解码 mydict[myconnection.fileno()] = nickname mylist.append(myconnection)#传入列表 print('connection', connNumber, ' has nickname :', nickname) tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】') while True: try: recvedMsg = myconnection.recv(1024).decode() if recvedMsg: print(mydict[connNumber], ':', recvedMsg) tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg) except (OSError, ConnectionResetError): try: mylist.remove(myconnection) except: pass print(mydict[connNumber], 'exit, ', len(mylist), ' person left') tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】') myconnection.close() return while True: connection, addr = sock.accept() print('Accept a new connection', connection.getsockname(), connection.fileno()) try: # connection.settimeout(5) buf = connection.recv(1024).decode() if buf == '1': connection.send(b'welcome to server!') # 为当前连接开辟一个新的线程 mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno())) mythread.setDaemon(True) mythread.start() else: connection.send(b'please go out!') connection.close() except: pass
#客户端 import socket import time import threading sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 4444)) sock.send(b'1') print(sock.recv(1024).decode()) nickName = input('input your nickname: ') sock.send(nickName.encode()) def sendThreadFunc(): while True: try: myword = input() sock.send(myword.encode()) # print(sock.recv(1024).decode()) except ConnectionAbortedError: print('Server closed this connection!') except ConnectionResetError: print('Server is closed!') def recvThreadFunc(): while True: try: otherword = sock.recv(1024) if otherword: print(otherword.decode()) else: pass except ConnectionAbortedError: print('Server closed this connection!') except ConnectionResetError: print('Server is closed!') th1 = threading.Thread(target=sendThreadFunc) th2 = threading.Thread(target=recvThreadFunc) threads = [th1, th2] for t in threads: t.setDaemon(True) t.start() t.join()