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


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! 😀


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.