我们在前面的文章中普通的socket并不能同时处理多个客户端,当一个客户端在与服务器连接时,其它客户端只能排队。而sockerserver则不同,它可以并发地处理多个客户端请求。
import socketserver
'''
每一个客户端请求过来,都会实例化 MyTCPHandler
'''
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
"跟客户端所有的交互都是在handle里完成的"
while True:
try:
self.data = self.request.recv(1024).strip()
print("{0} wrote:".format(self.client_address[0]))
print(self.data)
if not self.data:
print("输入为空")
self.request.send(bytes("输入为空", "utf-8"))
else:
self.request.send(self.data.upper())
except ConnectionResetError :
print("客户已断开连接")
break
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
#server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) # 实例化一对一的连接对象
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) # 实例化多并发的连接对象(多线程)
server.serve_forever()
客户端并没有什么区别:
import socket
HOST, PORT = "localhost", 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
while True:
data = input("输入字符")
try:
sock.sendall(bytes(data + "\n", "utf-8"))
received = str(sock.recv(1024), "utf-8")
finally:
print("Sent: {0}".format(data))
print("Received: {0}".format(received))
sock.close()
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx