socketserver
server 服务端
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self): # self.request 相当于 conn
while True:
msg = self.request.recv(1024).decode('utf-8')
if msg == 'q':
self.request.close()
break
print(msg)
info = input('>>>')
self.request.send(info.encode('utf-8'))
if __name__ == '__main__':
# 实例化
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyServer)
# 一直启动
server.serve_forever()
client1 客户端
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 8080))
while True:
msg = input('>>>')
if msg == 'q':
break
sk.send(msg.encode('utf-8'))
ret = sk.recv(1024).decode('utf-8')
print(ret)
sk.close()
client2
import socket sk = socket.socket() sk.connect(('127.0.0.1', 8080)) while True: msg = input('>>>') if msg == 'q': break sk.send(msg.encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close()