系列博文的传送门:http://www.cnblogs.com/lastpairs/p/6993237.html
客户端代码github地址 https://github.com/xxyjskx1987/lastpairswebapp
服务器端代码github地址 https://github.com/xxyjskx1987/lastpairsnodeserver
项目演示地址 http://www.tanmiba.com/
后端采用express进行搭建,express的使用方式如下
var express = require(‘express‘); var app = express(); //设置跨域请求的域名 app.all(‘*‘, function(req, res, next) { res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Origin", ""); next(); }); //设置监听端口 app.set(‘PORT‘, 3000); var server = app.listen(app.get(‘PORT‘),function(err){ if(err){ console.error(‘server error:%s‘,err && ess.message); return; } console.log(‘server listening at :::‘,app.get(‘PORT‘)); });
在express中使用socket.io,并且通过域名限制ws连接,模拟跨域
var io = require(‘socket.io‘)(server); //通过域名限制ws连接 io.origins((origin, callback) => { if (origin !== ‘http://www.tanmiba.com‘) { return callback(‘origin not allowed‘, false); } callback(null, true); }); //使用socket.io io.sockets.on(‘connection‘, function (socket) { console.log("connection"); socket.on(‘commonsay‘,function(data){ console.log("commonsay:" + data); //广播 io.sockets.emit(‘commonsay‘, data); }); socket.on(‘disconnect‘,function(){ console.log("disconnect"); }); });
express中对session的简单使用
var session = require(‘express-session‘); app.use(session({ resave: false, saveUninitialized: true, secret:‘recommand 128 bytes random string‘, cookie:{maxAge:60*1000*1000} }));
时间: 2024-10-07 06:13:23