From 9977dedf6ea544fc339d622f237176cef1bc36c9 Mon Sep 17 00:00:00 2001 From: Philip Horger Date: Fri, 23 Dec 2011 11:06:04 -0800 Subject: [PATCH 1/3] Added ability to close from another thread or greenlet --- socket_io.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/socket_io.py b/socket_io.py index 11c573d..82b92a2 100644 --- a/socket_io.py +++ b/socket_io.py @@ -139,6 +139,7 @@ def on_disconnect(self, client): def __init__(self): self.clients = {} + self.closed = False def _handle(self, info): command = info['command'] @@ -236,10 +237,14 @@ def send(data, info): # run the server buffer = '' - while 1: + while not self.closed: buffer += sock.recv(4096) index = buffer.find('\0') while index >= 0: data, buffer = buffer[0:index], buffer[index+1:] self._handle(json.loads(data)) index = buffer.find('\0') + cleanup() + + def close(self): + self.closed = True From bf4b83ce6dfc2dbd3602d3de745655fa5e768762 Mon Sep 17 00:00:00 2001 From: Philip Horger Date: Fri, 23 Dec 2011 11:07:44 -0800 Subject: [PATCH 2/3] Fixed require() search path bug --- socket_io.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/socket_io.py b/socket_io.py index 82b92a2..6a84b53 100644 --- a/socket_io.py +++ b/socket_io.py @@ -218,7 +218,9 @@ def listen(self, ws_port, py_port=None): os.close(handle) # run that script in node.js - process = subprocess.Popen(['node', path]) + env = os.environ + env["NODE_PATH"] = NodePath() + process = subprocess.Popen(['node', path], env=env) def cleanup(): process.kill() os.remove(path) @@ -248,3 +250,6 @@ def send(data, info): def close(self): self.closed = True + +def NodePath(): + return os.path.join(os.path.dirname(__file__), "node_modules") From 33abd014f4bc2d24a2b52ef7c7f208a7e89dec11 Mon Sep 17 00:00:00 2001 From: Philip Horger Date: Fri, 23 Dec 2011 11:10:06 -0800 Subject: [PATCH 3/3] Some worst-case-scenario handling for errors in node process --- socket_io.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/socket_io.py b/socket_io.py index 6a84b53..e8e1acf 100644 --- a/socket_io.py +++ b/socket_io.py @@ -223,7 +223,8 @@ def listen(self, ws_port, py_port=None): process = subprocess.Popen(['node', path], env=env) def cleanup(): process.kill() - os.remove(path) + if os.path.exists(path): + os.remove(path) atexit.register(cleanup) # make sure we can communicate with node.js @@ -240,7 +241,11 @@ def send(data, info): # run the server buffer = '' while not self.closed: - buffer += sock.recv(4096) + response = sock.recv(4096) + if response == "": + print "Node.js <-> Python socket broke in Socket.IO" + break + buffer += response index = buffer.find('\0') while index >= 0: data, buffer = buffer[0:index], buffer[index+1:]