gen gen - 1 year ago 335
JSON Question

connecting python to javascript for two-direction communication

I would like to serve queries from a javascript code by python. But I am not experienced in this field at all. What I would like to build is something like this:

1. request.js:

for (var i=0; i<10; i++)


x = 0
while connected:
if request:
x = x + 1

I heard about JSON, but don't know if I should use it. (?)

Could you please give me some code examples or guides how to implement the two files above?

Answer Source

What you need is a socket server on the python end and a client/request server on the javascript end.

For the python server side, refer to SocketServer, (example taken from there as well), one thing you have to make sure is to have the socket go past NAT (possibly port forwarding). One other alternative is Twisted which is a very powerful framework, i believe it has functionality to send data through NAT.

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the

    def handle(self):
        # self.request is the TCP socket connected to the client = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        # just send back the same data, but upper-cased

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

On the JavaScript there are many frameworks that allow socket connections, here are a few


<script src="/"></script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    socket.emit('my other event', { my: 'data' });


var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server


_jssocket.setCallBack(event, callback);

Hope this help!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download