简体   繁体   中英

Node.js and Web Sockets

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM