npm原文
Express应用程序的WebSocket端点。允许您像任何其他类型的路由一样定义WebSocket端点,并应用常规的Express中间件。WebSocket支持是在ws库的帮助下实现的
cnpm install --save express-ws//安装好后node-modoules目录里会增加一个express-ws包
将此行添加到Express应用程序,即bin/www文件:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
app.use(function (req, res, next) {
console.log('middleware');
req.testing = 'testing';
return next();
});
app.get('/', function(req, res, next){
console.log('get route', req.testing);
res.end();
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket', req.testing);
});
app.listen(3000);
- leaveRouterUntouched:设置此项以true防止express-ws修改Router原型。启用此选项后applyTo,您必须手动.ws启用要启用的每个路由器。
- wsOptions:传递给WebSocketServer构造函数的Options对象。任何ws特定功能所必需的。
wsInstance.app
wsInstance.applyTo(router)