-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
211 lines (152 loc) · 6.02 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//EXPRESS SERVER*****************************************************
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer();
server.on('request', (app));
//const server = require('http').createServer(app);
/*
server.listen(8080, 'localhost', function () {
console.log('Server listening on port 8080')
})
*/
server.listen(80, '138.197.220.209', function () {
console.log('Server listening on port 80')
})
//*******************************************************************
//WEBSOCKET SERVER***************************************************
const io = require('socket.io').listen(server);
//*******************************************************************
//MIDDLEWARE CODE****************************************************
//Body parser (JSON)
const bodyParser = require('body-parser');
app.use(bodyParser.json());
//*******************************************************************
//MONGO CODE*********************************************************
const mongodb = require('mongodb');
//set mongo client (native)
const mongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017/chatApp';
//*******************************************************************
//WEBSOCKET ROUTES****************************************************
let connections = [];
let users = [];
let messages = [];
//connect
io.sockets.on('connection', (socket) => {
//add new socket connection to array
connections.push(socket);
console.log('Connected: ' + connections.length + " Connections Open");
//pass array of users already online, to ALL clients
socket.emit('userArrayToClients', users);
//pass array of existing messages to client
socket.emit('msgArrayToClient', messages);
//disconnect
socket.on('disconnect', () => {
//remove socket from connections array
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: ' + connections.length + " Connections Remaining");
//and remove user from users array (if they are logged in)
if (socket.userName){
users.splice(users.indexOf(socket.userName), 1);
//communciate updated array back to all clients
io.sockets.emit('userArrayToClients', users);
}
})//end on('disconnect
//receive new message from client
socket.on('msgObjectToServer', (data) => {
//add message (object) to array
messages.push(data);
//send SINGLE object back to all clients
io.sockets.emit('msgObjectToClients', data);
})
//receive new user login from client
socket.on('newUserToServer', (data) => {
//add new user to array
users.push(data);
//attach username to socket object (for removal from array upon disconnect)
socket.userName = data;
//communciate updated array back to ALL clients
io.sockets.emit('userArrayToClients', users);
})
}) //end on('connection
//*******************************************************************
//EXPRESS HTTP ROUTES ******************************************************
//-------------------------------------------
//GET
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.get('/css/main.css', function(req, res) {
res.sendFile((__dirname + '/public/css/main.css'));
});
app.get('/js/main.js', function(req, res) {
res.sendFile((__dirname + '/public/js/main.js'));
});
//-------------------------------------------
//POST
//post for submitButton
app.post('/register', function(req, res) {
//connect to Mongo
mongoClient.connect(url, (err, db) => {
if (err){
res.send('Unable to connect to Mongo: ' + err);
}else{
console.log('Connected to ' + url);
}
//reference existing collection
const userCollection = db.collection('users');
//see if username already exists
userCollection.find({userName: req.body.userName}).toArray((err, dbResult) => {
if(err){
res.send('Database query error');
} else if (dbResult.length){
res.send('Username already exists in database');
} else {
console.log('No records found');
insertDoc();
}
});
function insertDoc(){
//insert req.body to Mongo
userCollection.insert(req.body, (err, dbResp) => {
if(err){
res.send('Unable to insert records: ' + err);
}else{
res.send(dbResp.insertedCount + ' doc inserted');
}
db.close;
});
} //end function
}) //end mongoClient.connect
}); // end app.post('/register'
//POST for goButton
app.post('/', function(req, res) {
//first check if user is already in array
if (users.includes(req.body.userName)){
res.send(JSON.stringify({error: 'You are already logged in\n....on a differenr window'}));
return;
}
//connect to Mongo
mongoClient.connect(url, (err, db) => {
if (err){
res.send(JSON.stringify({error: 'Unable to connect to Mongo: ' + err}));
}else{
console.log('Connected to ' + url);
}
//reference existing collection
const userCollection = db.collection('users');
//see if username exists
userCollection.find({userName: req.body.userName}).toArray((err, dbResult) => {
if(err){
res.send(JSON.stringify({error: 'Database query error'}));
} else if (dbResult.length){
//returns an array and we just want first & only one
res.send(JSON.stringify(dbResult[0]));
} else {
res.send(JSON.stringify({error: 'Username does not exist in database'}));
}
});
}) //end mongoClient.connect
}); // end app.post('/'
//-------------------------------------------