crawf
crawf

Reputation: 9658

Simple nodeJS example not working with socket.io

Have been struggling all day trying to make this simple example work using socket.io. I've tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.

When running the script, it shows this...

2 May 20:57:47 - socket.io ready - accepting connections

But visiting the index.html page doesnt show a client has even connected.

index.html

<html>
<head>
<script type="text/javascript" src="socket.io.js"></script> 
<script type="text/javascript"> 
    var socket = new io.Socket('localhost',{'port':8090});

    socket.connect();

    socket.on('connect', function(){
        console.log('connected');
        socket.send('hi!'); 
    });

    socket.on('message', function(data){ 
        console.log('message recived: ' + data);
    });

    socket.on('disconnect', function(){
        console.log('disconected');
    });
</script> 
</head>
<body></body>
</html>

server.js

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

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('<h1>Hello world</h1>'); 
});
server.listen(8090);

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

    client.on('message', function(){ 
        console.log('message arrive');
        client.send('some message');
    });

    client.on('disconnect', function(){
        console.log('connection closed');
    });
});

Any ideas on what I could be doing wrong? No console messages whatsoever are being displayed. Notably, when i use Firebug to look at the index.html page, no scripts are being embedded, which is odd..Not sure what could be causing that.

Upvotes: 6

Views: 13055

Answers (4)

vipulsodha
vipulsodha

Reputation: 634

Use this on the client side as the path !

<script type="text/javascript" src="/socket.io/socket.io.js"></script> 

Upvotes: 1

mzalazar
mzalazar

Reputation: 6586

yes, and comment the following line:

// server.listen(8090);

Upvotes: 0

generalhenry
generalhenry

Reputation: 17319

You're not serving up socket.io.js (or the flash file).

I'd recomend using the CDN:

<script src="http://cdn.socket.io/stable/socket.io.js"></script>

or alternatively use express to serve the socket.io.js file.

edit:

err actually looking closer you're also not serving up index.html again express could work but for the simple example:

var fs = require('fs');
var index = fs.readFileSync('index.html');
//note the readFileSync is done only in the first tic
.
.
.
res.writeHead(200, {'Content-Type': 'text/html'}); 
res.end(index); 

Upvotes: 8

noli
noli

Reputation: 15996

You're not loading the socket.io library properly in your index.html file. Try this:

<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script> 

Upvotes: 9

Related Questions