nodejs 執行個體 使用 Express + Socket.IO 搭建多人聊天室

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

 https://cnodejs.org/topic/51d51cd8d44cbfa3047926ba 作者 nswbmw

詳細內容大家可以看這個。

由於時間久遠,很多代碼都到期了。我剛更新了app.js代碼。

/** * Module dependencies. */var express = require(‘express‘)    , http = require(‘http‘)    , path = require(‘path‘);var app = express();// all environmentsapp.set(‘port‘, process.env.PORT || 3000);app.set(‘views‘, __dirname + ‘/views‘);app.set(‘view engine‘, ‘jade‘);var favicon = require(‘serve-favicon‘);//需安裝app.use(favicon(__dirname + ‘/public/favicon.ico‘));var morgan = require(‘morgan‘);//需安裝app.use(morgan(‘dev‘));var bodyParser = require(‘body-parser‘);//需安裝// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: false }))// parse application/jsonvar cookieParser = require(‘cookie-parser‘);//需安裝app.use(cookieParser());//app.use(app.route);app.use(express.static(path.join(__dirname, ‘public‘)));var users = {};//儲存線上使用者列表的對象app.get(‘/‘, function (req, res) {    if (null == req.cookies.user) {        res.redirect(‘/signin‘);    } else {        res.sendFile(__dirname + ‘/views/index.html‘);    }});app.get(‘/signin‘, function (req, res) {    res.sendFile(__dirname + ‘/views/signin.html‘);});app.post(‘/signin‘, function (req, res) {    if (users[req.body.name]) {        //存在,則不允許登陸        res.redirect(‘/signin‘);    } else {        //不存在,把使用者名稱存入 cookie 並跳轉到首頁        res.cookie("user", req.body.name, {maxAge: 1000*60*60*24*30});        res.redirect(‘/‘);    }});var server = http.createServer(app);var io = require(‘socket.io‘).listen(server);io.sockets.on(‘connection‘, function (socket) {    //有人上線    socket.on(‘online‘, function (data) {        //將上線的使用者名稱儲存為 socket 對象的屬性,以區分每個 socket 對象,方便後面使用        socket.name = data.user;        //users 對象中不存在該使用者名稱則插入該使用者名稱        if (!users[data.user]) {            users[data.user] = data.user;        }        //向所有使用者廣播該使用者上線資訊        io.sockets.emit(‘online‘, {users: users, user: data.user});    });    //有人發話    socket.on(‘say‘, function (data) {        if (data.to == ‘all‘) {            //向其他所有使用者廣播該使用者發話資訊            socket.broadcast.emit(‘say‘, data);        } else {            //向特定使用者發送該使用者發話資訊            //clients 為儲存所有連線物件的數組            //var clients = io.sockets.clients();            var clients= io.sockets.sockets;            //遍曆找到該使用者            clients.forEach(function (client) {                if (client.name == data.to) {                    //觸發該使用者用戶端的 say 事件                    client.emit(‘say‘, data);                }            });        }    });    //有人下線    socket.on(‘disconnect‘, function() {        //若 users 對象中儲存了該使用者名稱        if (users[socket.name]) {            //從 users 對象中刪除該使用者名稱            delete users[socket.name];            //向其他所有使用者廣播該使用者下線資訊            socket.broadcast.emit(‘offline‘, {users: users, user: socket.name});        }    });});server.listen(app.get(‘port‘), function(){    console.log(‘Express server listening on port ‘ + app.get(‘port‘));});

工具,webstorm

nodejs 執行個體 使用 Express + Socket.IO 搭建多人聊天室

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.