【问题标题】:Node JS push server send/receiveNode JS 推送服务器发送/接收
【发布时间】:2013-03-31 08:14:07
【问题描述】:

我正在尝试设置一个节点 js 服务器来向我的浏览器应用推送通知。我有一个基本示例,但我想知道如何在握手时从客户端将数据发送到服务器。

我需要向服务器发送用户 ID 之类的信息,因此当收到通知时,可以将其路由回用户。

我的服务器看起来像这样

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');

app.listen(8000);

function handler ( req, res ) {
    res.writeHead( 200 );
    res.end('node working');
};

io.sockets.on( 'connection', function ( socket ) {

  socket.volatile.emit( 'notification' , "blah" );
});

我的客户看起来像这样

 var socket = io.connect('http://localhost:8000');

  socket.on('notification', function (data) {
    //prints data here
  });

【问题讨论】:

    标签: javascript jquery node.js socket.io


    【解决方案1】:

    在 socket.io 中,emit 本质上类似于任何其他事件处理程序(例如 jQuery 的 .on('click'...));您声明事件并发送数据。在服务器上,您添加.on('event', ...) 以捕获请求并对其进行处理。

    socket.io 的首页显示了这个服务器示例:

    var io = require('socket.io').listen(80);
    
    io.sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });
    

    这是给客户的:

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://localhost');
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    </script>
    

    听起来您要查找的部分是 socket.emit 部分。

    【讨论】:

      【解决方案2】:

      我过去做过这种事情,方法是在客户端上设置一个 cookie(你可能正在这样做),然后使用 socket.io 的 authorization 事件。您可以使用此事件来决定是否首先接受与用户的套接字连接。

      io.configure(function () {
        io.set('authorization', function (handshakeData, callback) {
      
          var cookie = handshakeData.headers.cookie;
      
          // parse the cookie to get user data...
      
          // second argument to the callback decides whether to authorize the client
          callback(null, true);
        });
      });
      

      在此处查看更多文档:https://github.com/LearnBoost/socket.io/wiki/Authorizing

      请注意,handshakeData.headers.cookie 只是 cookie 的字符串文字表示,因此您必须自己进行解析。

      【讨论】:

      • 谢谢,虽然 Kato 的另一个答案正是我想要的,但事实证明这也很有帮助。
      猜你喜欢
      • 2019-06-23
      • 2016-02-08
      • 1970-01-01
      • 2020-06-30
      • 2021-02-28
      • 2016-08-06
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多