创建SocketServer
使用SocketServer创建一个网络服务程序只需要几个简单的步骤:
(1)、创建处理request的类,创建方法为:继承BaseRequestHandler类,并重载handle()方法。该方法将被回调用做处理当前接收到的request。
注意:一般的做法是直接继承StreamRequestHandler或者DatagramRequestHandler。比如:
class MyTCPHandler(SocketServer.StreamRequestHandler):
(2)、实例化一个server基类(比如TCPServer)的对象,并发服务器地址和处理request的类作为参数传入。
(3)、使用server基类对象调用handle_request()或serve_forever()方法,即可处理一个或多个request。
(4)、如果需要创建多进程或多线程的服务器程序,则可以通过混合继承ForkingMixIn或ThreadingMixIn类来实现,比如:
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass //创建一个多线程的TCP服务器。
注意:ThreadingMixIn必须要放在TCPServer前面。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import SocketServer
import threading
from socket import *
from multiprocessing import Pool
from SocketServer import BaseRequestHandler as SRH
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
class TCP_ThreadedServers(SRH):
def handle(self):
getdata = ""
data = ""
while True:
getdata = self.request.recv(1024)
if getdata == "":
break
else:
print getdata
self.request.sendall(getdata)
class TCPClient():
def __init__(self):
ip = "192.168.126.128"
port = 50601
addr = (ip, port)
self.tcp_client = socket(AF_INET, SOCK_STREAM)
self.tcp_client.connect(addr)
def SendData(self, data):
self.tcp_client.send(data)
def Revdata(self):
revdata = self.tcp_client.recv(1024)
return revdata
def CloseConnect(self):
self.tcp_client.close()
def test(data):
tcp_client = TCPClient()
tcp_client.SendData(data)
response = tcp_client.Revdata()
print response + 'aa'
tcp_client.CloseConnect()
def main():
ip = "192.168.126.128"
port = 50601
addr = (ip, port)
server = ThreadedTCPServer(addr, TCP_ThreadedServers)
# server = SocketServer.UDPServer(addr, TCP_ThreadedServers) UDP server
server_thread = threading.Thread(target = server.serve_forever)
server_thread.daemon = False
server_thread.start()
p = Pool(4)
for i in range(30):
p.apply_async(test,(str(i),))
if __name__ == '__main__':
main()