简体   繁体   English

如何在相对路径上创建多个Node.js WebSocket

[英]How to create multiple Node.js websockets on relative path

For example, if I want to run: 例如,如果我想运行:

var http = require('http');
var s = http.createServer();
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
s.on('request', (request, response)=>{
// other codes
});
s.listen(process.env.PORT || 3000);
var a = new WebSocketServer('/a');
var b = new WebSocketServer('/b');
var c = new WebSocketServer('/c');

So ideally I want a to be process.env.host:process.env.PORT/a , likewise for b and c . 因此,理想情况下,我希望aprocess.env.host:process.env.PORT/a ,同样对于bc How will this be done? 怎么做? What's the correct syntax? 正确的语法是什么?

You can't have multiple servers on the same port. 同一端口上不能有多个服务器。 You can implement one webSocket server and then route the incoming requests based on the incoming URL to different code. 您可以实现一个webSocket服务器,然后根据传入URL将传入请求路由到不同的代码。 That should be all you need. 那应该是您所需要的。

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws, req) {
    const location = url.parse(req.url, true);
    // branch your code here based on location.pathname
});

If you want to be able to broadcast separately to each group based on their original path, then you can implement collections of connected sockets based upon the incoming path so you can broadcast to all in any particular connection. 如果希望能够根据其原始路径分别向每个组广播,则可以根据传入路径实现连接套接字的集合,以便可以在任何特定连接中向所有人广播。

If you're going to keep wanting more features like this, then perhaps you should use socket.io instead which has rooms and namespaces already built-in which does both of these for you. 如果您将继续想要更多这样的功能,那么也许应该使用socket.io代替,它已经内置了房间和名称空间,可以为您完成这两项工作。

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

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