简体   繁体   English

在Socket.IO和WS之间共享WebSocket连接

[英]Sharing a WebSocket connection between Socket.IO and WS

In an effort to be able to send binary data while utilizing Socket.IO's RPC functionality, I thought that I could use both Socket.IO and the WS module on the same server. 为了能够在利用Socket.IO的RPC功能的同时发送二进制数据,我认为我可以在同一台服务器上同时使用Socket.IO和WS模块。 Rather than opening up completely separate servers to make both connections, I am wondering if I can utilize the same HTTP server. 我想知道是否可以使用相同的HTTP服务器,而不是打开完全独立的服务器来建立两个连接。

Is it possible to use only one server created with http.createServer() for both Socket.IO and WS at the same time? 是否可以同时使用一个用http.createServer()创建的服务器同时用于Socket.IO和WS? To be clear, I anticipate creating both a Socket.IO connection and a regular WebSocket connection from the client. 为了清楚起见,我期望从客户端创建Socket.IO连接和常规WebSocket连接。 The following code creates protocol errors on the client side, presumably because both Socket.IO and WS are attempting to handle the connection. 以下代码在客户端创建协议错误,可能是因为Socket.IO和WS都试图处理连接。

var http = require('http');
var server = http.createServer(app);
server.listen(3000);

// Socket.IO
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
    // ...
}

// ws
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
    // ...
}

It turns out that this is possible with some configuration. 事实证明,这可以通过某种配置实现。 The trick is to tell Socket.IO not to destroy non-Socket.IO WebSocket connection requests, and then to put Socket.IO and WS on separate paths. 诀窍是告诉Socket.IO不要破坏nonSocket.IO WebSocket连接请求,然后将Socket.IO和WS放在不同的路径上。 Here is some messy example code, but it works while reusing the Socket.IO session ID for the secondary connection. 这是一些杂乱的示例代码,但它在重用Socket.IO会话ID进行辅助连接时有效。

var server = http.createServer(app);
server.listen(3000);

var WebSocketServer = require('ws').Server
var io = require('socket.io').listen(server);

io.set('destroy upgrade', false);
io.set('transports', ['websocket']);

io.sockets.on('connection', function (socket) {
    var wss = new WebSocketServer({
        server: server,
        path: '/anythingYouWant/' + socket.id
    });
    wss.on('connection', function(ws) {
        ws.on('message', function(message) {
            console.log(message);
        });
    });
});

As of 2016 I simply could assign the websocket module ws a path 截至2016年,我只需将websocket模块指定为路径即可

var wss = new WebSocketServer({ server: server, path: '/ws' }); //do not interfere with socket.io

No need to alter the socket.io side at all 根本不需要改变socket.io方面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM