将数据从WebSocket发送到Socket.io

4


我使用WebSocket接口连接WebSocket服务器。如果我想将从WebSocket服务器收到的数据通过我的WebSocket接口发送给通过HTTP服务器连接到我的客户端,我应该使用Socket.IO吗?

enter image description here

所以最终我将把socket.io附加到HTTP服务器上,并使用WebSocket接口获取数据,在消息到达时,通过socket.io发送给客户端。这是最佳设置吗?

代码示例:

// Require HTTP module (to start server) and Socket.IO
var http = require('http'),
    io = require('socket.io');
var WebSocket = require('ws');


var ws = new WebSocket('ws://localhost:5000');

// Start the server at port 8080
var server = http.createServer(function (req, res) {

    // Send HTML headers and message
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

ws.on('open', function open() {
    ws.send('something');
});

ws.on('message', function (data, flags) {
    // here the data will be send to socket.io
});

// Add a connect listener
socket.on('connection', function (client) {

    // Success!  Now listen to messages to be received
    client.on('message', function (event) {
        console.log('Received message from client!', event);
    });
    client.on('disconnect', function () {
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});
1个回答

0
是的,您的设计是正确的。
然而,有一件事需要记住,在身份验证之后要确保将消息发送给正确的客户端。我认为,由于使用WebSockets进行消息传递非常简单,所以很容易犯这种错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接