forked from aszx87410/nodejs_simple_chatroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
49 lines (38 loc) · 941 Bytes
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var user_count = 0;
//當新的使用者連接進來的時候
io.on('connection', function(socket){
//新user
socket.on('add user',function(msg){
socket.username = msg;
console.log("new user:"+msg+" logged.");
io.emit('add user',{
username: socket.username
});
});
//監聽新訊息事件
socket.on('chat message', function(msg){
console.log(socket.username+":"+msg);
//發佈新訊息
io.emit('chat message', {
username:socket.username,
msg:msg
});
});
//left
socket.on('disconnect',function(){
console.log(socket.username+" left.");
io.emit('user left',{
username:socket.username
});
});
});
//指定port
http.listen(process.env.PORT || 3000, function(){
console.log('listening on *:3000');
});