使用SocketServer创建一个网络服务程序,并且是多线程的,只需要几个简单的步骤:
(1)、创建处理request的类,创建方法为:继承BaseRequestHandler类,并重载handle()方法。该方法将被回调用做处理当前接收到的request。
注意:一般的做法是直接继承StreamRequestHandler或者DatagramRequestHandler。比如:
class MyTCPHandler(SocketServer.StreamRequestHandler):
(2)、实例化一个server基类(比如TCPServer)的对象,并发服务器地址和处理request的类作为参数传入。
(3)、使用server基类对象调用handle_request()或serve_forever()方法,即可处理一个或多个request。
参考alex教程上的,服务器端多线程方式监听,接收从客户端发送过来的命令cmd,执行cmd之后,将结果返回给客户端看。代码如下:
服务端代码,multithread_server.py:
1 import SocketServer 2 import commands,time 3 class MyTCPHandler(SocketServer.BaseRequestHandler): 4 def handle(self): 5 while True: 6 print "Got a new connection from ",self.client_address 7 cmd = self.request.recv(1024) 8 if not cmd: 9 print "Lost connection with",self.client_address 10 break 11 print ‘recv:‘,cmd 12 13 #commands.getstatusoutput execute cmd from client 14 15 cmd_result = commands.getstatusoutput(cmd) 16 17 18 #服务器发送的结果的长度 19 self.request.send(str(len(cmd_result[1]))) #cmd_result[0] result status, cmd_result[1] result content 20 21 #为防止粘包现象,sleep一下 22 time.sleep(0.2) 23 24 #服务器发送结果的内容 25 self.request.sendall(cmd_result[1]) 26 27 if __name__ == "__main__": 28 HOST,PORT = "localhost",999 29 30 server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCPHandler) 31 server.serve_forever() 32
客户端代码client.py
1 import socket 2 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 sock.connect((‘localhost‘,999)) 4 5 def recv_all(obj,msg_length): 6 raw_result = ‘‘ 7 while True: 8 if msg_length <=4096: 9 #data = once received 10 data = obj.recv(msg_length) 11 raw_result += data 12 break 13 else: 14 data = obj.recv(4096) 15 raw_result += data 16 msg_length = msg_length - 4096 17 18 return raw_result 19 20 21 while True: 22 user_input = raw_input("msg to send:").strip() 23 24 sock.send(user_input) 25 26 #res_size :接收到的结果长度 27 res_size = int(sock.recv(1024)) 28 29 print ‘received data size: ‘,res_size 30 31 #recv_all(sock,res_size): 接收到的结果内容 32 print "received data::",recv_all(sock,res_size) 33 34 sock.close()
时间: 2024-10-11 01:34:52