tcp网络编程_socketserver
服务端代码
import socketserver
import time
'''
socketserver的应用场景:
tcp协议的server端处理并发的客户端请求
'''
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
while True:
try:
content = conn.recv(1024).decode('utf-8')
conn.send(content.upper().encode('utf-8'))
time.sleep(0.2)
except ConnectionResetError:
break
server = socketserver.ThreadingTCPServer(('127.0.0.1', 9000), MyServer)
server.serve_forever()
客户端代码
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 9000))
while True:
sk.send(b'hello')
content = sk.recv(1024).decode('utf-8')
print(content)