TCP多线程聊天
- 服务器端
1 from socket import * 2 from threading import Thread 3 sockets = [] 4 def main(): 5 #创建server_socket套接字对象 6 server_socket = socket(AF_INET,SOCK_STREAM) 7 #绑定端口 8 server_socket.bind(('',8889)) 9 #监听 10 server_socket.listen() 11 #接收客户端的请求 12 while True: 13 client_socket,client_info = server_socket.accept() 14 sockets.append(client_socket) 15 #开启线程处理当前客户端的请求 16 t = Thread(target=readMsg,args=(client_socket,)) 17 t.start() 18 def readMsg(client_socket): 19 #读取客户端发送过来的消息 20 while True: 21 recv_data = client_socket.recv(1024) 22 #将消息发送给所有在线客户端 23 #遍历所有在线客户端列表 24 for socket in sockets: 25 socket.send(recv_data) 26 if __name__ == '__main__': 27 main()
- 客户端
1 from sock import * 2 from threading import Thread 3 def readMsg(client_socket): 4 while True: 5 recv_data = client_socket.recv(1024) 6 print('收到:',recv_data.decode('utf-8')) 7 def writeMsg(client_socket): 8 while True: 9 msg = input('>') 10 client_socket.sent(msg.encode('utf-8')) 11 #创建客户端套接字对象 12 client_socket = socket(AF_INET,SOCK_STREAM) 13 #调用connect()连接服务器 14 client_socket.connect(('192.168.0.107',8888)) 15 #开启一个线程处理客户端的读取消息 16 t = Thread(target=readMsg,args=(client_socket,)) 17 t.start() 18 #开启一个线程处理客户端的发送消息 19 t = Thread(target=writeMsg,args=(client_socket,)) 20 t.start()
正是江南好风景