首页 > 其他分享 >socketserver实现多用户连接简单代码

socketserver实现多用户连接简单代码

时间:2024-10-16 22:11:42浏览次数:6  
标签:__ socketserver 多用户 代码 client print data self

1.服务端

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
print("{} wrote".format(self.client_address[0]))
print(self.data)
self.request.send(self.data.upper())
except ConnectionResetError as e:
print("error", e)
break

if __name__=="__main__":
HOST, PORT = "0.0.0.0", 22222
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

2.客户端

import socket
client = socket.socket()
client.connect(("localhost", 22222))

while True:
msg = input(">>:").strip()
if len(msg) == 0:continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print( data.decode())
client.close()

标签:__,socketserver,多用户,代码,client,print,data,self
From: https://www.cnblogs.com/circlecircle/p/18471041

相关文章