简体   繁体   English

Node.js和Web套接字

[英]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. 我已经运行了一个node.js服务器,当我导航到该URL时,可以显示“ hello world”或Twitter提要。

Issue is I cannot get any communication to happen between the node.js instance and the websocket defined on the client of another page. 问题是我无法在node.js实例与另一页的客户端上定义的websocket之间发生任何通信。

Does anyone have any ideas? 有人有什么想法吗?

Thanks so much. 非常感谢。

Do yo run node.js behind some proxy? 您是否在某些代理后面运行node.js? Some proxies (eg ngnix) don't support http 1.1 and http 1.1 is necessary for websockets. 某些代理(例如ngnix)不支持http 1.1,并且websockets必须使用http 1.1。

Look here for WebSocket libraries compatible with Node.JS. 在此处查找与Node.JS兼容的WebSocket库。 Node.JS does not provide WebSocket support out of the box, you need to install additional library. Node.JS不提供开箱即用的WebSocket支持,您需要安装其他库。 Socket.io would be sufficient. Socket.io就足够了。

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. 当我在Chrome中刷新页面时,可以看到正在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. 现在唯一的问题是触发所有这些javascript套接字警报。

Any ideas? 有任何想法吗?

Thanks, Dan 谢谢,丹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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