首先安装express4,参考http://www.expressjs.com.cn/starter/generator.html
npm install express-generator -g
然后创建express项目
express -e myapp
这样就创建了一个基于ejs模板的express后台服务项目.
接下来安装soket.io
npm install socket.io --save
现在所需要的模块已经安装好了,默认情况下express启动后,监听在3000端口,这里是想将express和websocket都在80端口监听,需要修改bin目录下的www文件,找到
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('enlarge-server:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
以上便是监听逻辑,做以下修改即可达到目的:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('enlarge-server:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
//修改端口为80
var port = normalizePort(process.env.PORT || '80');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
//websocket跟express绑定
var io = require('socket.io')(server);
io.on('connection', function(socket) {
//收到客户端的websocket连接请求
console.log('connection:' + socket.request.connection.remoteAddress);
socket.on('scan', function(data) {
//......
})
});
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
这样就修改好了.
这里再分享一个http请求来了后跟websocket进行通信的经验,其实因为http和websocket是运行在同一个服务上,一般想的方法是在http请求来的时候拿到websocket连接对象然后发送消息给客户端,很遗憾的是因为socket.io的绑定是在www下,而http一般是在router类来实现,请求来是拿不到相关连接对象,如果强制使用全局对象来实现也不好维护和增加泄漏风险,遇到这种情况时可以使用另外一种办法,就是在请求来时创建一个socket.io的客户端请求来连接本地的websocket服务,示例如下:
// routers/connect.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end("{ code: 'ok'}");
//连接本地服务
var io = require("socket.io-client");
let socket = io.connect("ws://localhost");
if (req.query.config != undefined && req.query.config != '') {
console.log('redirect config:' + req.query.config);
//发送数据到指定事件
socket.emit('scan', JSON.parse(req.query.config));
} else {
console.log('redirect config is empty');
}
});
module.exports = router;
全部代码放在github上Enlarge-Server