-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
97 lines (73 loc) · 2.25 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
89
90
91
92
93
94
95
96
97
//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];
var quoteObj = require('./quote');
var clientSession = require('./user')
var currentQuote = new quoteObj('Jason', 'Added a like system');
var quoteHistory = [];
io.on('connection', function(socket) {
var name;
var sessions = [];
console.log("Client with id: " + socket.id + " connected.");
var newSession = new clientSession(socket.id);
sessions.unshift(newSession);
socket.on('sendname', function(data) {
name = data;
});
socket.on('sendquote', function(data) {
if (name != null) {
var newQuote = new quoteObj(name, data, this.id);
console.log(this.id);
currentQuote = newQuote;
io.sockets.emit('newquote', newQuote);
quoteHistory.unshift(newQuote);
console.log(quoteHistory);
if (quoteHistory.length > 10) {
quoteHistory.pop();
}
io.sockets.emit('quotehistory', quoteHistory);
}
});
socket.on('like', function(data) {
currentQuote.like += 1;
io.sockets.emit('newlike', currentQuote);
quoteHistory.shift();
quoteHistory.unshift(currentQuote);
io.sockets.emit('quotehistory', quoteHistory);
});
if (currentQuote != null) {
socket.emit('newquote', currentQuote);
socket.emit('newlike', currentQuote);
}
if (quoteHistory != null) {
socket.emit('quotehistory', quoteHistory);
}
});
function broadcast(event, data) {
sockets.forEach(function(socket) {
socket.emit(event, data);
});
}
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function() {
var addr = server.address();
console.log("Quote server listening at", addr.address + ":" + addr.port);
});