写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。
'''服务端'''
import socket
from threading import Thread
s = socket.socket()
s.bind(
('127.0.0.1',8848)
)
s.listen(5)
print('等待客户端连接中...')
def server(conn):
# 将服务端接受收的功能放入多线程调用函数
while True:
res = conn.recv(1024)
print(res.decode('utf-8'))
if res == 'q':
break
conn.send(res.upper())
if __name__ == '__main__':
while True:
conn, addr = s.accept()
print(f'用户{addr}已经连接')
t = Thread(target=server,args=(conn,))
# 创建线程
t.start()
'''客户端'''
import socket
from threading import Thread
c = socket.socket()
c.connect(
('127.0.0.1',8848)
)
while True:
msg = input('请输入发送至服务端消息:').strip()
if msg == 'q':
break
c.send(msg.encode('utf-8'))
data = c.recv(1024)
print(data.decode('utf-8'))