服务端代码
import socketserver
'''
创建一个请求处理类,并且这个类要继承BaseRequestHandler,并且还有重写父亲类里的handle()
实例化TCPServer ,并且传递server ip 和 你上面创建的请求处理类 给这个TCPServer
server.handle_request() #只处理一个请求
server.serve_forever() #处理多个一个请求,永远执行
'''
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
if not self.data:
break
print('来自客户端:',self.client_address)
print('>>>',self.data.decode())
self.request.send(self.data.upper())
except ConnectionResetError as e:
print(e)
break
if __name__ == '__main__':
HOST,PORT = 'localhost',8080
server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
客户端代码
import socket
client = socket.socket()
client.connect(('localhost',8080))
while True:
data = input('>>>')
if not data:
continue
client.send(data.encode('utf-8'))#data必须为字节序列
data = client.recv(1024).decode()
print('>>>',data)
client.close()