I am learning to use HTML5 WebSockets and as part of that I am writing a server in Python so I can know the nitty gritty of how they work. I created one the other day that worked pretty well, but I wanted to expand it so it would support multiple endpoints with each endpoint being a different "service" which can handle websocket clients.
At the moment, my implementation works with spawning processes and such (I am using multiprocessing instead of threading since I read that threading isn't really multithreading in CPython and that's what I think I am using (default install on Ubuntu 12.04)), but I am having trouble sending received client sockets to the service processes.
Here is how I send them (this runs in a loop):
#get a new client
conn, addr = server.accept()
print "Client connected from", addr
request = conn.recv(4096)
response, close, service = self.handshake(request)
print "Invalid request from", addr
client = WebSockets.WebSocketClient(conn, addr)
"""Base class for all services."""
def __init__(self, manager):
self.manager = manager
self.clientConnQueue = self.manager.Queue()
self.shutdownFlag = multiprocessing.Event()
File "./WebSocketServer.py", line 183, in <module>
File "./WebSocketServer.py", line 180, in main
File "./WebSocketServer.py", line 67, in runServer
File "<string>", line 2, in put
File "/usr/lib/python2.7/multiprocessing/managers.py", line 758, in _callmethod
conn.send((self._id, methodname, args, kwds))
TypeError: expected string or Unicode object, NoneType found
Pass socket to another process is not a trivial thing. Look, for example, this question: Can I open a socket and pass it to another process in Linux
Anyway, OS processes or threads is not what you really want for implement websocket server, because of large memory overhead. Look at smth with nonblocking sockets... eg, Tornado http://www.tornadoweb.org/documentation/websocket.html