-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
88 lines (75 loc) · 2.76 KB
/
server.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
cfenv = require("cfenv"),
MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Environment auslesen
var appEnv = cfenv.getAppEnv();
// Webserver auf den Port x schalten
server.listen(appEnv.port, appEnv.bind, function() {
console.log("Server starting on " + appEnv.url);
})
// MONGODB
var mongoDBUrl = 'mongodb://localhost:27017/MongoChatDB';
var mongoDBServiceConfig = appEnv.getService("MongoChatDB");
if (mongoDBServiceConfig) {
mongoDBUrl = mongoDBServiceConfig.credentials.uri;
}
MongoClient.connect(mongoDBUrl, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to MongoDB server at " + mongoDBUrl);
db.close();
});
app.configure(function(){
// statische Dateien ausliefern
app.use(express.static(__dirname + '/public'));
});
// wenn der Pfad / aufgerufen wird
app.get('/', function (req, res) {
// so wird die Datei index.html ausgegeben
res.sendfile(__dirname + '/public/index.html');
});
// wenn der Pfad /clear aufgerufen wird
app.post('/clear', function (req, res) {
// Chat löschen
MongoClient.connect(mongoDBUrl, function(err, db) {
assert.equal(null, err);
console.log("Clear chat");
db.collection('chat').drop();
db.close();
res.status(200).send('OK');
});
});
// Websocket
io.sockets.on('connection', function (socket) {
// Konversation aus der DB lesen
MongoClient.connect(mongoDBUrl, function(err, db) {
assert.equal(null, err);
db.collection('chat').find({}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
for (var i=0; i< result.length; i++)
socket.emit('chat', { zeit: result[i].zeit, name: result[i].name, text: result[i].text });
} else {
console.log('No chat(s) found with defined "find" criteria!');
}
db.close();
// der Client ist verbunden
socket.emit('chat', { zeit: new Date(), text: 'Du bist nun mit dem Server verbunden!' });
});
});
// wenn ein Benutzer einen Text senden
socket.on('chat', function (data) {
// so wird dieser Text an alle anderen Benutzer gesendet
io.sockets.emit('chat', { zeit: new Date(), name: data.name || 'Anonym', text: data.text });
MongoClient.connect(mongoDBUrl, function(err, db) {
assert.equal(null, err);
var collection = db.collection('chat');
collection.insertOne({zeit: new Date(), name: data.name || 'Anonym', text: data.text });
db.close();
});
});
});