Javascript 将数据从websocket发送到socket.io

Javascript 将数据从websocket发送到socket.io,javascript,node.js,websocket,socket.io,Javascript,Node.js,Websocket,Socket.io,我使用websocket接口连接到websocket服务器。如果我想将通过websocket接口从websocket服务器接收的数据发送到通过http服务器连接到我的客户端,我应该使用socket.io吗 因此,在最后,我将socket.io连接到http服务器和websocket接口以获取数据,并且在出现消息时,将通过socket.io发送到客户端。这是最好的设置吗 代码示例: // Require HTTP module (to start server) and Socket.IO va


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

因此,在最后,我将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');
    });

});
//需要HTTP模块(启动服务器)和Socket.IO
var http=require('http'),
io=require('socket.io');
var WebSocket=require('ws');
var ws=newwebsocket('ws://localhost:5000');
//在端口8080启动服务器
var server=http.createServer(函数(req,res){
//发送HTML标题和消息
文书标题(200{
“内容类型”:“文本/html”
});
res.end('你好插座情人!');
});
监听服务器(8080);
//创建一个Socket.IO实例,并将其传递给服务器
var socket=io.listen(服务器);
ws.on('open',function open(){
ws.send('something');
});
ws.on('message',函数(数据,标志){
//在这里,数据将被发送到socket.io
});
//添加一个连接侦听器
socket.on('connection',函数(客户端){
//成功!现在收听要接收的消息
client.on('message',函数(event){
log('从客户端收到消息!',事件);
});
client.on('disconnect',function(){
间隔时间;
log('服务器已断开连接');
});
});

是的,您的设计是正确的

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