@@ -3,38 +3,41 @@ const http = require('http').Server(app);
33const io = require ( 'socket.io' ) ( http ) ;
44const util = require ( 'util' ) ;
55const port = 3000 ;
6- const clients = [ ] ;
6+ const clients = [ ] ; //track connected clients
77
88//Server Web Client
99app . get ( '/' , function ( req , res ) {
1010 res . sendFile ( __dirname + '/index.html' ) ;
1111} ) ;
1212
13+ //make one reference to event name so it can be easily renamed
14+ const chatEvent = "chatMessage" ;
15+
1316//When a client connects, bind each desired event to the client socket
14- io . on ( 'connection' , function ( socket ) {
17+ io . on ( 'connection' , socket => {
1518 //track connected clients via log
1619 clients . push ( socket . id ) ;
17- let clientConnectedMsg = 'User connected ' + util . inspect ( socket . id ) + ', total: ' + clients . length ;
18- io . emit ( 'chat message' , clientConnectedMsg ) ;
20+ const clientConnectedMsg = 'User connected ' + util . inspect ( socket . id ) + ', total: ' + clients . length ;
21+ io . emit ( chatEvent , clientConnectedMsg ) ;
1922 console . log ( clientConnectedMsg ) ;
2023
2124 //track disconnected clients via log
22- socket . on ( 'disconnect' , function ( ) {
25+ socket . on ( 'disconnect' , ( ) => {
2326 clients . pop ( socket . id ) ;
24- let clientDisconnectedMsg = 'User disconnected ' + util . inspect ( socket . id ) + ', total: ' + clients . length ;
25- io . emit ( 'chat message' , clientDisconnectedMsg ) ;
27+ const clientDisconnectedMsg = 'User disconnected ' + util . inspect ( socket . id ) + ', total: ' + clients . length ;
28+ io . emit ( chatEvent , clientDisconnectedMsg ) ;
2629 console . log ( clientDisconnectedMsg ) ;
2730 } )
2831
2932 //multicast received message from client
30- socket . on ( 'chat message' , function ( msg ) {
31- let combinedMsg = socket . id . substring ( 0 , 4 ) + ': ' + msg ;
32- io . emit ( 'chat message' , combinedMsg ) ;
33+ socket . on ( chatEvent , msg => {
34+ const combinedMsg = socket . id . substring ( 0 , 4 ) + ': ' + msg ;
35+ io . emit ( chatEvent , combinedMsg ) ;
3336 console . log ( 'multicast: ' + combinedMsg ) ;
3437 } ) ;
3538} ) ;
3639
3740//Start the Server
38- http . listen ( port , function ( ) {
41+ http . listen ( port , ( ) => {
3942 console . log ( 'listening on *:' + port ) ;
4043} ) ;
0 commit comments