Question

Help to build python ForkingTCPServer. This server returns an error when client connects to the server. When I use ThreadingTCPServer instead of ForkingTCPServer it works fine. socketFileIO module contains functions for pickle to/from socket: http://code.activestate.com/recipes/577667-pickle-tofrom-socket/

server.py:

import SocketServer, time 
from socketFileIO import write, read

class MyClientHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print self.client_address
        data=read(self.request)
        print 'Client:', data
        time.sleep(10) # for testing
        write(self.request,data)
        self.request.close()

HOST, PORT = '', 50007
server = SocketServer.ForkingTCPServer((HOST, PORT), MyClientHandler)
server.serve_forever()

client.py:

import socket
from socketFileIO import write, read
HOST = '127.0.0.1'
PORT = 50007
data=["A","B","C","End"]
for x in data:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    write(s,x)
    y=read(s)
    print 'Server:', y
    s.close()

Error:

----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 1469)
Traceback (most recent call last):
  File "c:\Python26\lib\SocketServer.py", line 283, in _handle_request_noblock
    self.process_request(request, client_address)
  File "c:\Python26\lib\SocketServer.py", line 525, in process_request
    pid = os.fork()
AttributeError: 'module' object has no attribute 'fork'
----------------------------------------

I have a several other questions:

  1. How to shutdown the server by sending data "End" from client ?
  2. How to restrict the number of connections (for example no more then 5) ?
Was it helpful?

Solution

Your fork question was already answered in comments.

For "how to shut down the server": in a similar application (but much older Python version and using xmlrpc), I used a loop invoking one request at a time until a "stop" variable was set. This appears to be supported directly in Python 2.7 now: in your threaded server, call shutdown() on the server instance, from one of the request-handler threads. (Not sure if this is available in 2.6, I de-installed my old 2.6 version a couple of months ago.) I.e.:

class MyClientHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        ...
        # if we're supposed to shut down the server, do that
        if somecond:
            self.server.shutdown()

For limiting the number of connections: there's nothing built-in that I can see, but if you redefined the process_request handler you could count the number of active threads and wait for one to finish if there are "too many" outstanding (or work it however else you like). See the ThreadingMixIn class in SocketServer.py and compare it to the max_children code in ForkingMixIn.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top