server端
1 ###websocket_server### 2 import socket 3 import threading 4 5 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 6 7 sock.bind(('localhost', 900)) 8 9 sock.listen(5) 10 print('Server', socket.gethostbyname('localhost'), 'listening ...') 11 12 mydict = dict() 13 mylist = list() 14 15 16 # 把whatToSay传给除了exceptNum的所有人 17 def tellOthers(exceptNum, whatToSay): 18 for c in mylist: 19 if c.fileno() != exceptNum: 20 try: 21 c.send(whatToSay.encode()) 22 except: 23 pass 24 25 26 def subThreadIn(myconnection, connNumber): 27 nickname = myconnection.recv(1024).decode() 28 mydict[myconnection.fileno()] = nickname 29 mylist.append(myconnection) 30 print('connection', connNumber, ' has nickname :', nickname) 31 tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】') 32 while True: 33 try: 34 recvedMsg = myconnection.recv(1024).decode() 35 if recvedMsg: 36 print(mydict[connNumber], ':', recvedMsg) 37 tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg) 38 39 except (OSError, ConnectionResetError): 40 try: 41 mylist.remove(myconnection) 42 except: 43 pass 44 print(mydict[connNumber], 'exit, ', len(mylist), ' person left') 45 tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】') 46 myconnection.close() 47 return 48 49 50 while True: 51 connection, addr = sock.accept() 52 print('Accept a new connection', connection.getsockname(), connection.fileno()) 53 try: 54 # connection.settimeout(5) 55 buf = connection.recv(1024).decode() 56 if buf == '1': 57 connection.send(b'welcome to server!') 58 59 # 为当前连接开辟一个新的线程 60 mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno())) 61 mythread.setDaemon(True) 62 mythread.start() 63 64 else: 65 connection.send(b'please go out!') 66 connection.close() 67 except: 68 pass
client端
1 #####socket_client#### 2 import socket 3 import time 4 import threading 5 6 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 8 sock.connect(('localhost', 900)) 9 sock.send(b'1') 10 print(sock.recv(1024).decode()) 11 nickName = input('input your nickname: ') 12 sock.send(nickName.encode()) 13 14 15 def sendThreadFunc(): 16 while True: 17 try: 18 myword = input() 19 sock.send(myword.encode()) 20 # print(sock.recv(1024).decode()) 21 except ConnectionAbortedError: 22 print('Server closed this connection!') 23 except ConnectionResetError: 24 print('Server is closed!') 25 26 27 def recvThreadFunc(): 28 while True: 29 try: 30 otherword = sock.recv(1024) 31 if otherword: 32 print(otherword.decode()) 33 else: 34 pass 35 except ConnectionAbortedError: 36 print('Server closed this connection!') 37 38 except ConnectionResetError: 39 print('Server is closed!') 40 41 42 th1 = threading.Thread(target=sendThreadFunc) 43 th2 = threading.Thread(target=recvThreadFunc) 44 threads = [th1, th2] 45 46 for t in threads: 47 t.setDaemon(True) 48 t.start() 49 t.join()
测试结果