views:

339

answers:

4

Hello,

I've got a node.js server running and I can get it to show "hello world" or a twitter feed when I navigate to the url.

Issue is I cannot get any communication to happen between the node.js instance and the websocket defined on the client of another page.

Does anyone have any ideas?

Thanks so much.

A: 

Look here for WebSocket libraries compatible with Node.JS. Node.JS does not provide WebSocket support out of the box, you need to install additional library. Socket.io would be sufficient.

fuwaneko
Thanks for the response. I got something going now, when I refresh the server I can see in my shell window requests are coming in. However the only websocket event ever fired is onclose -- Any ideas?Thanks a lot
dan
Without the code I have no ideas.
fuwaneko
A: 

Do yo run node.js behind some proxy? Some proxies (e.g. ngnix) don't support http 1.1 and http 1.1 is necessary for websockets.

Mike Korobov
A: 

Okay, so I got this working(I think)

Again, Client-side code:

<script src="./Socket.IO/socket.io.js"></script>
<script>
    io.setPath('./Socket.IO/');

    var socket = new io.Socket('jayz.danstanhope.webfactional.com', { 'port': 80 });

    socket.on('connect', function () {
        alert('connect');
    });
    socket.on('message', function (msg) {
        alert('message' + msg);
    });
    socket.on('close', function () {
        alert('close');
    });
    socket.on('disconnect', function () {
        alert('disconnect');
    });
    socket.connect();

</script>

Server-side code:

var sys = require("sys")
  , fs = require("fs")
  , path = require("path")
  , http = require("http");
var io = require('/home/danstanhope/webapps/htdocs/Socket.IO-node');

var server = http.createServer(function (req, res) {
    //your normal server code
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Hello world');
    res.end();
});

server.listen(26970);
server = io.listen(server);
server.on('connection', function(client){
    sys.log('client connected');
});

When I refresh the page in Chrome I can see logs being written in Shell.

Here's what I see:

danstanhope@web146 htdocs]$ node server.js
9 Aug 19:19:37 - socket.io ready - accepting connections
9 Aug 19:19:40 - Initializing client with transport "websocket"
9 Aug 19:19:40 - Client 21789167495444417 connected
9 Aug 19:19:40 - client connected
9 Aug 19:19:40 - Client 21789167495444417 disconnected

The only issue now is getting any of those javascript socket alerts to fire.

Any ideas?

Thanks, Dan

Dan