【问题标题】:Node.js and Web SocketsNode.js 和 Web 套接字
【发布时间】:2011-03-25 06:12:09
【问题描述】:

我有一个 node.js 服务器正在运行,当我导航到该 url 时,我可以让它显示“hello world”或 twitter 提要。

问题是我无法在 node.js 实例和另一个页面的客户端上定义的 websocket 之间进行任何通信。

有人有什么想法吗?

非常感谢。

【问题讨论】:

标签: node.js websocket


【解决方案1】:

你会在一些代理后面运行 node.js 吗?一些代理(例如 ngnix)不支持 http 1.1,而 websocket 需要 http 1.1。

【讨论】:

    【解决方案2】:

    Look here 用于与 Node.JS 兼容的 WebSocket 库。 Node.JS 不提供开箱即用的 WebSocket 支持,您需要安装额外的库。 Socket.io 就足够了。

    【讨论】:

    • 感谢您的回复。我现在有一些事情发生了,当我刷新服务器时,我可以在我的 shell 窗口中看到请求正在进来。但是,唯一触发的 websocket 事件是 onclose - 有什么想法吗?非常感谢
    【解决方案3】:

    好的,所以我得到了这个工作(我想)

    再次,客户端代码:

    <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>
    

    服务器端代码:

    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');
    });
    

    当我在 Chrome 中刷新页面时,我可以看到在 Shell 中写入的日志。

    这是我看到的:

    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
    

    现在唯一的问题是让这些 javascript 套接字警报触发。

    有什么想法吗?

    谢谢, 丹

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多