Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js socket.io-client + python socketio

node.js socket.io-client + python socketio

Problem

I am trying to use Socket.IO to allow my Node.JS app to communicate with a Python Backend. I want Node.JS to act as the client and Python to act as the server, so I am using the socket.io-client Node.JS module in addition to the gevent-socketio python module.

https://github.com/LearnBoost/socket.io-client https://github.com/abourget/gevent-socketio

Here is my python server:

#!/usr/bin/env python
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace

class MyNamespace(BaseNamespace):
    def on_foobar(self,data):
        print 'received method for foobar'
        print data


server = SocketIOServer(('localhost', 1234),resource=MyNamespace,policy_server=False)
print 'SocketIO server listening...'
server.serve_forever()

Here is my Node.JS server (acting as client):

#!/usr/bin/env node
var io = require('socket.io-client');
var PySocket = io.connect('localhost:1234');
PySocket.emit('foobar',{'key1':'value1'});

For some reason, the python server is not seeing the connection. can anyone point out what I am missing?

Problem courtesy of: ejang

Solution

You'll need a little bit more on the Python side.

The Namespace object is not to be passed as a parameter to the SocketIOServer object. That resource (later renamed to namespace) is only the name of the path to be recognized (like http://localhost/[namespace]/[rest of the socket.io protocol path]. I agree there is an overlap in terminology, but we rarely deal with a resource/namespace other than socket.io.

Now, for your python IO-server to run, you'll need to wrap it using some framework.. to actually dispatch some incoming request to the correct handler. That handler must execute socketio_manage() and this is the function where you should pass your Namespace object as a parameter. Also, your framework will probably want to serve other files, like the .swf ... gevent-socketio doesn't do that for you. Also, if you want your python process to do anything (like interact with databases, load some configuration files), I recommend you pick a framework, as it will ease your life for mostly anything you'll need to do.

If you really just want to have a socket-type of server, from node.js to python, then why not use the standard TCP/UDP sockets ? In that case, you wouldn't need the overhead of a framework, the encoding/decoding of the Socket.IO protocol, etc..

What is your particular use case ? Maybe this could shed some light on the way to go.

Solution courtesy of: abourget

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js socket.io-client + python socketio

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×