標籤:express 代碼 網路 span function callback ext als hub
系列博文的傳送門: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.ioio.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}}));
基於網路聊天室的社交遊戲 -- nodejs、express、socket.io-server