2016-11-06 94 views
2

我在写一个使用nodejs-ws模块的websocket服务器,但服务器只能在服务器的根目录下,所以我怎样才能使它像localhost:3000/chat这样的子路由器?如何让websocket服务器在路由器上?

我需要你的帮助,非常感谢!

回答

0

工作例如:

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"); 
}); 
+0

非常感谢,你能告诉我如何在快递使用呢? – laoqiren

0

你能告诉我如何在快递使用呢?

为了航线的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!'); 
    }); 
});