网络编程使用socketserver,通常包括以下几步:
一、定义类,并继承socketserver.BaseRequestHandler
二、重写handle方法
三、实例化TCPServer,并传递IP,PORT等信息,并把定义的类传进去。
四、server.server_forever()。
服务端:
import socketserver
class MYTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data=self.request.recv(1024).strip()
print ("{} wrote".format(self.client_address[0]))
print(self.data)
self.request.send(self.data.upper())
except ConnectionResetError as e:
print ("err",e)
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
client=socket.socket()
client.connect(("localhost",9999))
while True:
msg=input(">>>")
if len(msg)==0:
continue
client.send(msg.encode())
data=client.recv(1024)
print ("recv:",data.decode())