Example create socket connection between Node JS and Python


I build an experiment which is a multiplayer Pong game that using NodeJS and Django. This game need to build communication between browser in mobile phone as GamePad and browser in my laptop as display. Then, I facing this performance issue which there are delay between button get pressed in mobile browser and pong bar movement in laptop.

Then, I try to make it faster by change the display from browser into Python GUI. I’m wondering if I can make socket connection between displayer and NodeJS, it will gain performance 100% since there no websocket anymore.

After look at few documentation, I do a small stuff to make NodeJS can communicate with Python using socket.

Here is the results:

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var net = require(‘net’);

var HOST = ‘127.0.0.1’;
var PORT = 7000;

// Create a server instance, and chain the listen function to it
net.createServer(function(socket) {
    console.log(‘CONNECTED: ‘ + socket.remoteAddress +’:’+ socket.remotePort);
   
    // Add a ‘data’ event handler to this instance of socket
    socket.on(‘data’, function(data) {
        console.log(‘DATA ‘ + socket.remoteAddress + ‘: ‘ + data);
        socket.write(‘This is your request: "’ + data + ‘"’);
    });
   
    // Add a ‘close’ event handler to this instance of socket
    socket.on(‘close’, function(data) {
        console.log(‘Socket connection closed… ‘);
    });
}).listen(PORT, HOST);

console.log(‘Server listening on ‘ + HOST +’:’+ PORT);

And Python socket:

1
2
3
4
5
6
7
8
9
10
11
import socket

if __name__ == "__main__":
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((‘127.0.0.1’, 7000))

    client.sendall("Hello")
    data = client.recv(1024)
    client.close()

    print ‘Received’, repr(data)

Then we can see the results by:

1
2
3
4
5
yodi@mac:~/socket $ node server.js
Server listening on 127.0.0.1:7000
CONNECTED: 127.0.0.1:49829
DATA 127.0.0.1: Hello
Socket connection closed…
1
2
yodi@mac:~/socket $ python python-socket.py
Received ‘This is your request: "Hello"’

It’s amazing that we can do real-time between event-based NodeJS and Python! 😀

PS: this is my realtime pong multiplayer:

https://www.youtube.com/watch?v=IK8-3qUqncE


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.