2015-10-10 124 views
2


将数据发送至socket.io

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

enter image description here

所以在最后我将不得不socket.io附着到HTTP服务器和网页套接字接口获取的数据和消息的情况下,来的就通过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'); 
    }); 

}); 

回答

0

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

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