NodeJS,Python

Example create socket connection between Node JS and Python

30 Jan , 2013  

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.
More…

,

NodeJS

Example using Express 3 and Socket.io on the same ports

27 Jan , 2013  

Here is a quick example of using Express and Socket.io together. Usually, you landed into this pages because having problem like “express socket.io not found”, “static files in express to find socket.io.js” or someother else.

1. package.json

1
2
3
4
5
6
{
 "name" : "example-express-socketio",
 "version" : "0.1.0",
 "dependencies" : {"socket.io" : "0.9.6",
                   "express": "3.0.0"}
}

2. server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var express = require('express'),
    socketio = require('socket.io'),
    app = express();
    http = require('http');

app.use("/", express.static(__dirname));

var server = http.createServer(app);
var io = socketio.listen(server);

var index = "<!doctype html>
             <html>
               <head>
                   <script src=/socket.io/socket.io.js></script>
                       <script>
                               var socket = io.connect('http://192.168.2.6:4000');
                               function test() {
                                            socket.emit('foo', 'Boo', function(data) {
                                                    alert(data);
                                    });
                                }
                        </script>
                </head>
                <body>
                <button onclick='test();'>Test</button>
            </html>";

app.get('/', function(req, res) {
    res.send(index);
});

io.sockets.on('connection', function(socket) {
    socket.on('foo', function(name, f) {
            f('Hello ' + name);
    });
});

server.listen(4000, "0.0.0.0");

Remember to change this “http://192.168.2.6:4000” into yours IP or localhost.

3. Run

1
node server.js

and open “http://localhost:4000”.

Voila! 😀

,