<p>您可以使用<a href="https://docs.python.org/2/library/socketserver.html" rel="nofollow">SocketServer</a>包。文档中给出了一些可能对您有用的小示例。以下是tcp服务器的扩展示例:</p>
<pre><code>import SocketServer
import os
import logging
import json
FORMAT = '[%(asctime)-15s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
class MyServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
# By setting this we allow the server to re-bind to the address by
# setting SO_REUSEADDR, meaning you don't have to wait for
# timeouts when you kill the server and the sockets don't get
# closed down correctly.
allow_reuse_address = True
request_queue_size = 10
def __init__(self, port):
self.host = os.uname()[1]
self.port = port
SocketServer.TCPServer.__init__(self, (self.host,self.port), MyTCPHandler)
logging.info( "Server has been started on {h}:{p}".format(h=self.host,p=self.port) )
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
# max length is here 2048 chars
s = self.request.recv(2048).strip()
logging.info( "received: {d}".format(d=s) )
# here you may parse the received string
obj = json.loads( s )
# here just send something back to server
self.request.sendall("got it")
PORT = 11111
if __name__ == "__main__":
# Create the server, binding to localhost on port 11111
#server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server = MyServer( PORT )
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
</code></pre>