7

I’m using NodeJS v0.4.8 and the latest Version of socket.io from

npm install socket.io

on Ubuntu:

Linux mars 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

The following code unfortunately doesn't produce any output, wheter on client, nor on server side.

Does anybody have a clue?

SERVER-SIDE

var http = require('http'),  
io = require('socket.io'),
fs = require('fs'),
sys = require('sys');

respcont = fs.readFileSync('testclient.js');

server = http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(respcont);
});
server.listen(8082);

var socket = io.listen(server); 
socket.on('connection', function(client){ 

    sys.puts("New client is here!");
    client.send("hello world");

    client.on('message', function(msg) { sys.puts("client has sent:"+msg); }) ;
    client.on('disconnect', function() { sys.puts("Client has disconnected"); }) ;
}); 

CLIENT-SIDE

<html>
<body>
<script type="text/javascript" src="http://localhost:8082/socket.io/socket.io.js"></script>
<script> 
    var socket = new io.Socket(null,{port:8082,rememberTransport:true,timeout:1500});
    socket.connect();
    socket.on('connect', function() { 
        console.log('connected to server'); 
        socket.send('Hi Server...'); 
    });

    socket.on('message', function() { 
        console.log('received a message!');
    });

    socket.on('disconnect', function() { 
        console.log('disconnected from server'); 
    });

</script> 
</body>
</html>

The output from NodeJS (NOT the sys.puts("...") calls) is:

info - socket.io started debug - served static /socket.io.js debug - client authorized info - handshake authorized info - handshaken b61a5c2751c1c8c8493db4b79d19e779

franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
helix
  • 196
  • 1
  • 2
  • 10

3 Answers3

4

Express 3.0 + Socket.io working example

server ( app.js )

var express = require('express');
    var app = express.createServer();
    var socket = require('socket.io');
    app.configure(function(){
        app.use(express.static(__dirname + '/'));
    });
    var server = app.listen(8081);
    var io = socket.listen(server);
    io.sockets.on('connection', function (socket) {
        console.log("connnect");
        socket.on('disconnect', function (socket) {
        console.log("disconnect");
     });
}); 

client ( index.html )

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:8081');
</script>

you can fork the code using the link below https://github.com/sreekumar-kr/Expree3.0---Socket.IO

sreekumar
  • 211
  • 3
  • 4
  • Please do not post answers that are just links to your blog. See the [faq section on promotion](http://stackoverflow.com/faq#promotion) and this Meta Stack Overflow discussion: [How can I link to an external resource in a community-friendly way?](http://meta.stackexchange.com/questions/94022/how-can-i-link-to-an-external-resource-in-a-community-friendly-way) – Josh Darnell Aug 01 '12 at 15:35
  • Thank you for improving your answer =) You can add your link back in, just as long as it's not the *only* thing in your answer (and the link is relevant, which it appears to be). – Josh Darnell Aug 02 '12 at 03:39
3

I also(like Derrish) like to use express framework to simplify my work(AWESOME :)). You can download and extract this sample from http://dl.dropbox.com/u/314941/socketio.zip. I believe you don't even have to install these modules because I have bundled them locally(just run) thanks to npm :).

How to install:

alfred@alfred-laptop:~/tmp/socketio$ uname -a
Linux alfred-laptop 2.6.35-28-generic #50-Ubuntu SMP Fri Mar 18 19:00:26 UTC 2011 i686 GNU/Linux
alfred@alfred-laptop:~/tmp$ wget http://dl.dropbox.com/u/314941/socketio.zip
alfred@alfred-laptop:~/tmp$ unzip socketio.zip
alfred@alfred-laptop:~/tmp$ cd socketio/
alfred@alfred-laptop:~/tmp/socketio$ node -v
v0.4.7
alfred@alfred-laptop:~/tmp/socketio$ npm -v
1.0.6
alfred@alfred-laptop:~/tmp/socketio$ node app.js

The code:

app.js:

// npm install express
// npm install socket.io

var sys         = require('sys'),
        express = require('express'),
        app         = express.createServer('127.0.0.1'),
        io          = require('socket.io'); 

app.use(express.static(__dirname + '/public'));

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

app.listen(3000);

var socket = io.listen(app); 

socket.on('connection', function (client){ 
  // new client is here!
  setTimeout(function () {
        client.send('Waited two seconds!');
    }, 2000);

  client.on('message', function () {
  }) ;

  client.on('disconnect', function () {
  });
});

public/index.html:

<html>
<p id="text">socket.io</p>

<script src="socket.io/socket.io.js"></script> 
<script src="jquery-1.6.1.min.js"></script><!-- Downloaded Jquery -->

<script> 
    $(document).ready(function(){

        var socket  = new io.Socket(),
                text        = $('#text');

        socket.connect();

        socket.on('connect', function () {
            text.html('connected');
        });

        socket.on('message', function (msg) {
            text.html(msg);
        });

        socket.on('disconnect', function () {
            text.html('disconnected');
        });

    });
</script> 

Listing of my modules:

alfred@alfred-laptop:~/tmp/socketio$ npm ls
/home/alfred/tmp/socketio
├─┬ express@2.3.11 
│ ├── connect@1.4.6 
│ ├── mime@1.2.2 
│ └── qs@0.1.0 
└── socket.io@0.6.18

Installed modules(NOT necessary):

npm install express
npm install socket.io

Browser will display:

  1. socket.io on start, but probably you can't see this because it will be replaced with connected.
  2. connected when the user connects to socket.io.
  3. After 2 seconds it will display Waited two seconds!image
Alfred
  • 60,935
  • 33
  • 147
  • 186
  • 1
    Great, thankyou, your Example is working. It's weired, but I think this line: express.createServer('127.0.0.1'), with the explicit IP (instead of "localhost") notation has solved my problem. Thanks a lot! – helix Jun 21 '11 at 20:25
  • @Alfred "node app.js" command starts my socket.io server. but when i close terminal, server stop and clients are disconnect. So how can i make server always On and never stop.? – Ashok Gujjar Apr 07 '16 at 10:43
1

I took your example and dropped it in an a node app using express. Your HTML code was placed in a static HTML file under public. Your example worked fine. The code is shown below. I wanted to make sure both the socket.io script file and the HTML file were being served up properly.

var http = require('http'),  
    io = require('socket.io'),
    express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

if (!module.parent) {
  app.listen(9000);
  console.log("server started at %s", (new Date()).toUTCString());
  console.log("listening on port %d", app.address().port);
}


// socket.io 
var socket = io.listen(app); 
socket.on('connection', function(client){ 
    console.log("New client is here!");
    client.send("hello world");
    client.on('message', function(msg){ console.log("client has sent:"+msg); }) ;
    client.on('disconnect', function(){ console.log("Client has disconnected"); }) ;
    client.on('disconnect', function(){ }) 
 }); 
Derrish Repchick
  • 1,049
  • 8
  • 5
  • hi @Derrish, oke, that doesnt sound too bad, thank you. I have put the code you've shown in test.js, then I created a public folder and put index.html into this public folder. When I run "node test" and visit localhost:9000, I get an "Cannot GET /" Error. What is the right way to access this example from the Browser? Thank you. – helix Jun 20 '11 at 19:23
  • I believe any files in the static folder need to be addressed using their full path in the URL. http://localhost:9000/index.html – Derrish Repchick Jun 20 '11 at 19:59
  • 1
    OK, the example is working, but I don't get any output in the console. Do you get the texts ("New client is here, client has sent: ..." and so on) in the console? Which NodeJS/Socket.io Versions are you using? – helix Jun 20 '11 at 20:16
  • I suspect the socket.io.js file is not getting loaded in your browser. Have you confirmed that there are no script errors being reported by your browser? Make sure your script tag is referencing the correct path /socket.io/socket.io.js – Derrish Repchick Jun 20 '11 at 22:04