Last active
September 4, 2016 10:27
-
-
Save hieven/9ab4bdbc8b9e35d98549c6a240220f91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
app.use(express.static(__dirname + '/public')); | |
// 簡單建立兩個 endpoint 分給兩個頁面 lobby, room | |
app.get('/', (req, res) => { | |
res.sendFile('lobby.html', { root: __dirname + '/public/' }); | |
}); | |
app.get('/rooms', (req, res) => { | |
res.sendFile('room.html', { root: __dirname + '/public/' }); | |
}); | |
// 初始化 server 端的 socket.io | |
const server = require('http').Server(app); | |
const io = require('socket.io')(server); | |
// 對每一個 socket connection 都可以綁上 event listener | |
io.on('connection', socket => { | |
// 用 socket 自己的 id 作為 user id | |
socket.emit('new uid', { id: socket.id }); | |
// 當 client 端發出 "new message" 的 event 時 | |
// 會進入這個 callback | |
socket.on('new message', data => { | |
// 簡單地將說話者的 id 以及內容傳給其他 connection | |
// broadcast 的作用會廣播給除了自己以外的所有人 | |
socket.broadcast.emit('new message', { | |
id: socket.id, | |
content: data.content | |
}); | |
}); | |
}); | |
module.exports = server; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment