我正在写一个websocket服务器使用nodejs-ws模块,但服务器只能在服务器的根,所以我怎么能使它在子路由器像localhost:3000/聊天?
我需要你的帮助,非常感谢!工作示例:
var ws = require('ws');
var http = require('http');
var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');
var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
console.log("connection on /chat");
});
var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
console.log("connection on /notifications");
});
你能告诉我在快递中怎么用吗?
要用Express路由websockets,我宁愿使用Express -ws-routes
var express = require('express');
var app = require('express-ws-routes')();
app.websocket('/myurl', function(info, cb, next) {
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
cb(function(socket) {
socket.send('connected!');
});
});