-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
37 lines (28 loc) · 1.06 KB
/
index.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
var app = require('express')();
//create the server app
var http = require('http').Server(app);
var io = require('socket.io')(http);
var pg = require('pg');
//connection to database
var conString = "postgres://postgres:12345@localhost/postgres";
var client = new pg.Client(conString);
client.connect();
//provides the interface (index.html) file to client
app.get('/', function(req, res){
res.sendFile('index.html', {root: __dirname});
});
io.on('connection', function(socket){
//triggers on messages received
socket.on('chat message', function(user, msg){
// record the message on the database
client.query("INSERT INTO messages(chat_user, chat_message) values($1, $2)", [user, msg]);
//displays the message on the console
console.log(user + ' says ' + msg);
//broadcast the message to all the users (except the sender)
socket.broadcast.emit('chat message',user + ' says ' + msg);
});
});
//http server ready, listening for incoming connections on port:2000
http.listen(80, function(){
console.log('listening on *:80');
});