将数据从websocket发送到socket.io [英] Send data from websocket to socket.io

查看:179
本文介绍了将数据从websocket发送到socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我使用websocket接口连接到websocket服务器。如果我想通过我的websocket接口将我从websocket服务器收到的数据发送到通过http服务器连接到我的客户端,我应该使用socket.io吗?

I used websocket interface to connect to websocket server . what if i want send data that i receive from the websocket server through my websocket interface to client connected to me through http server , should i use socket.io ?

所以最后我将socket.io附加到http服务器和websocket接口以获取数据,如果消息将通过socket.io发送到客户端。这是最好的设置吗?

so at the end i will have socket.io attached to to http server and websocket interface to get data and in case of message come will be send to client through socket.io . is that the best setup ?

代码示例:

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

});


推荐答案

是的,你的设计是正确的。

Yes, your design is correct.

但是,您应该记住的一件事是在验证后将消息发送到正确的客户端。在我看来,犯这个错误很容易,部分原因是使用websockets进行消息传递的简单性。

However, one thing that you should keep in mind is take care of sending the message to the correct client after authentication. In my opinion, it is very easy to make this mistake, partially because of the simplicity of messaging using websockets.

这篇关于将数据从websocket发送到socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆