基於網路聊天室的社交遊戲 -- nodejs、express、socket.io-server

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.