写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。
客户端
# client 客户端
import socket
client = socket.socket()
client.connect(
('127.0.0.1', 8866)
)
while True:
cmd = input('hello>>: ').strip()
if not cmd:
continue
if cmd =='q':
break
client.send(cmd.encode('utf-8'))
data = client.recv(1024)
print(data)
client.close()
服务端
# server服务端
import socket
from threading import Thread
import threading
server = socket.socket()
server.bind(
('127.0.0.1', 8866)
)
server.listen(2)
def action(conn):
while True:
data = conn.recv(1024)
print(data)
conn.send(data.upper())
if __name__ == '__main__':
while True:
conn, addr = server.accept()
p = threading.Thread(target=action, args=(conn,))
p.start()
server.close()