2
我用的WebSocket接口连接到WebSocket伺服器。如果我想通过我的websocket接口将通过websocket服务器接收的数据发送给通过http服务器连接到我的客户端,我应该使用socket.io?
所以在最后我将不得不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');
});
});