-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
43 lines (38 loc) · 823 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
var mongo = require('mongodb').MongoClient;
var client = require('socket.io').listen(8080).sockets;
mongo.connect('mongodb://127.0.0.1/chatroom',function(e,db){
if(e){
throw e;
}
client.on('connection',function(socket){
var chat = db.collection('chats');
sendStatus = function(s){
socket.emit('status',s);
}
chat.find().sort({_id:1}).toArray(function(e,res){
if (e) {
throw e;
}
socket.emit('output',res);
})
socket.on('input',function(data){
var date = data.date;
var message = data.message;
if (message=='') {
sendStatus('啥都不填你发个球啊!')
}
else{
chat.insert({
message:message,
date:date
},function(){
client.emit('output',[data]);
sendStatus({
message:'已发送',
clear:true
})
})
}
})
})
});