使用线程实现socket服务端同时响应多个客户端

时间:2021-08-19 22:16:36
 1 #利用线程实现服务端同时响应多个客户端
 2 #!-*- conding:utf-8 -*-
 3 import socket
 4 import threading
 5 import time
 6 addr=("127.0.0.1",8808)
 7 conn=socket.socket()
 8 conn.connect((addr))
 9 def pro(aa):
10     data = conn.recv(1024)
11     print(str(data, encoding="utf-8"))
12 
13     conn.sendall(bytes(aa, encoding="utf-8"))
14 while 1:
15     aa = input("请输入\n")
16    
17     pro(aa)
18 conn.close()
19 
20 
21 import socket
22 import threading
23 import time
24 addr=("127.0.0.1",8808)
25 conn=socket.socket()
26 conn.bind((addr))
27 conn.listen(5)
28 def client(conn1):
29     conn1.send(bytes("welcom to server",encoding="utf-8"))
30     while 1:
31         data=conn1.recv(1024)
32         # if not data:
33         #     break
34         conn1.sendall(data+bytes("服务器收到",encoding="utf-8"))
35         print("ok")
36     conn1.close()
37 
38 while True:
39     sock,ar=conn.accept()
40     print(ar)
41     a=threading.Thread(target=client,args=(sock ,))
42     a.start()
43     #a.join()
44     print("biaoji")