from socketserver import BaseRequestHandler, TCPServer
def xyz_to_msg(x : int,y : int,z : int) -> str:
assert len(str(x)) <= 5, 'The length of x cannot be greater than 5!'
assert len(str(y)) <= 5, 'The length of y cannot be greater than 5!'
assert len(str(z)) <= 5, 'The length of z cannot be greater than 5!'
msg_x = str(x).rjust(5,'0') if x > 0 else '-' + str(-x).rjust(4,'0')
msg_y = str(y).rjust(5,'0') if y > 0 else '-' + str(-y).rjust(4,'0')
msg_z = str(z).rjust(5,'0') if z > 0 else '-' + str(-z).rjust(4,'0')
msg = msg_x + msg_y + msg_z
return msg
# 继承BaseRequestHandler这个base class,并重定义handle()
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
# self.request is the TCP socket connected to the client
while True:
# 8192代表每次读取8192字节
recvdata = self.request.recv(1024)
if not recvdata:
break
msg = xyz_to_msg(1175,42,293)
# print(type(msg))
self.request.send(msg.encode())
if __name__ == '__main__':
# 第一对参数是(host, port)
serv = TCPServer(('127.0.0.1', 9999), EchoHandler)
serv.serve_forever()
用socketserver创建一个TCP服务器
最新推荐文章于 2022-07-01 14:00:36 发布