我试图将自定义对象设置为记录here的TCP处理程序类的属性。在我的例子中,服务器和客户端处理程序都需要一个自定义对象:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The request handler 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 set_custom_object(self, custom_object):
self.customObject = custom_object
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
# Call a custom method of the custom object over the data
self.data = self.customObject.custom_method(self.data)
# Send back the processed data
self.request.sendall(self.data)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
如何将 customObject 绑定到处理程序类?
BaseRequestHandler 提供了一组可覆盖的方法,但无法找到它们被调用的位置。
class BaseRequestHandler:
"""Base class for request handler classes.
This class is instantiated for each request to be handled. The
constructor sets the instance variables request, client_address
and server, and then calls the handle() method. To implement a
specific service, all you need to do is to derive a class which
defines a handle() method.
The handle() method can find the request as self.request, the
client address as self.client_address, and the server (in case it
needs access to per-server information) as self.server. Since a
separate instance is created for each request, the handle() method
can define arbitrary other instance variariables.
"""
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
self.setup()
try:
self.handle()
finally:
self.finish()
def setup(self):
pass
def handle(self):
pass
def finish(self):
pass