【问题标题】:Socket.io Basic web socket connection with url?Socket.io 与 url 的基本网络套接字连接?
【发布时间】:2019-02-15 10:28:51
【问题描述】:

我的客户端正在向此 URL 发出 WebSocket 请求:ws://localhost:3000/feed/XBTMUR

在我的服务器中,我有运行 Express 的 NodeJ。我想使用 Socket.io 来监听连接到这个 URL 的客户端并定期发送 feed 数据。 我试过了,但它不起作用:

var app = require('../app');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
/**
 * Listen on provided port, on all network interfaces.
 */

var io  = require('socket.io')(server);
var feed =
    io.of('/feed/XBTMUR').on('connection', function (socket) {

        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data) {
            console.log(data);
        });
    });

io.on('connection', function(socket) {
    console.log('a user connected, id ' + socket.id);
    socket.on('disconnect', function() {
        console.log('a user disconnected, id '  + socket.id);
    })
})
setInterval(()=>{
    io.sockets.emit('this', { receivers: 'everyone'});
},1000)

server.listen(port);

客户端没有使用 Socket io。

【问题讨论】:

  • 如果您在服务器端使用套接字 io 客户端,我不确定是否是个好主意。顺便说一句,你为什么在服务器端使用它?
  • 我无法控制客户端。我改用 npm ws 库解决了它
  • 这个库是个很好的选择:)

标签: javascript node.js sockets websocket socket.io


【解决方案1】:

我在阅读documentation时感觉实现是错误的。

var feed = io.of('/feed')     // `/feed` is the namespace
.on('connection', function (socket) {

    socket.to('XBTMUR', { hello: 'world' });  // `XBTMUR` is the room / socket id

});

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2013-03-18
    • 2016-03-30
    • 2021-07-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多