forked from Rajesh-Royal/ChatAppSocketIO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (58 loc) · 2.11 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
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
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs'); // required for file serving
// var imageCompression = require('browser-image-compression'); //image compression
var port = process.env.PORT || 4000;
app.use(express.static(__dirname));
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.username = "Anonymouse";
console.log(socket.username + ' connected on socket ', socket);
socket.on('change_username', (data) => {
if (data.username == '') socket.username = 'Anonymouse';
else socket.username = data.username;
socket.broadcast.emit('chat message', '<span class="username">A new User ' + socket.username + ': Joined The Chatroom </span>');
console.log("username = " + data.username);
})
socket.on('chat message', (msg) => {
io.emit('chat message', '<span class="username">' + socket.username + ': </span>' + msg);
});
socket.on('typing', (data) => {
socket.broadcast.emit('typing', { username: socket.username });
})
socket.on('stop typing', () => {
socket.broadcast.emit('stop typing', {
username: socket.username
});
})
//serving images
socket.on('base64 file', function (msg) {
console.log('received base64 file from' + socket.username);
//console.log(msg.filename);
// socket.broadcast.emit('base64 image', //exclude sender
io.sockets.emit('base64 file', //include sender
{
username: socket.username=='' ? 'Anonymouse' : socket.username,
file: msg.file,
fileName: msg.fileName
}
);
});
// io.on('connection', function(socket){
// try {
// fs.readFile(__dirname + '/images/rajesh.jpg', function(err, buf){
// socket.emit('image', { image: true, buffer: buf.toString('base64') });
// console.log('image file is initialized');
// });
// } catch (error) {
// console.log(error.message);
// }
// });
});