⬆️ ⬇️

Development of a simple chat on Socket.IO [2016] \ Node.js

Hello everyone, dear habrakhabrovtsy! Recently, I started learning node.js and got to the most interesting, namely Socket.Io . After studying the information on the Internet, I could not find a detailed guide on this module, so I had to dig myself. Some will say that you can understand for yourself what is written on the module site , but some of this will not be enough to understand the base of web-sockets, so I decided to write this article for such people, namely, in the most “clear” example - chat .



Module installation



So let's get down to it ?! First we need to actually install our Socket.Io , how to install it you can read here , and for those who do not understand, I will explain: there is a client and a server , you need to put the module itself through npm into the project folder (for this you need to open in advance it in the console, and then install):



npm install socket.io --save 


After you have installed the module, the folder “node_modules” will appear in the project folder ( where you put it ) .



Now we have to install the .js file of the module itself in the folder with the project (the .js file will be used on the client) , put it from here => * tyk * . You download the archive, and from there you have to get the file "socket.io.js" and transfer it to the folder with the project.

')

For those who do not understand, the structure of the project folder with the chat should be as follows:



  chat: (The folder itself)
 | node_modules
 | --socket.io (Inside <i> node_modules </ i>)
 | socket.io.js 


After you have downloaded the .js file and installed the module, you can proceed to the next step.



Installation of additional modules



You will also need modules such as:



1. express # To create a server

2. log4js # Excellent logger

3. http # The http server itself



express:



 npm install express --save 


log4js:



 npm install log4js 


http:



 npm install http 


After all these procedures, the “node_modules” folder should be replenished ( * it seems logical * ). Now you can start developing our chat!



Chat development



Now we can proceed with the development, but before that, we need to create a .js-file in the directory of the project “chat.js” in which we will write our chat. First, open our chat.js and connect all the modules in this way:



 var express = require('express'); //  express var app = express(); var server = require('http').Server(app); //  http  app var io = require('socket.io')(server); //  socket.io     var log4js = require('log4js'); //    var logger = log4js.getLogger(); //    log4js   


That's all we need to connect at the beginning. Next, create a variable where we specify our listening port (for the server) :



 var port = 3000; //     


After that you can prologirovat script start in this way:



 logger.debug('Script has been started...'); // . 


Next put on the "wiretapping" for the server port in this way:



 server.listen(port); //         localhost:3000    


Now we have to make sure that the client that connects to our localhost: 3000 server receives a batch of files such as index.html; main.css; socket.io; main.js; to display the page with our chat.



This is done simply, we create the “public” folder in the root of the project, and we drop our “socket.io.js” there , and then we create there such files as index.html, main.js, main.css (We will not use this for visibility) . Our project structure should be something like this:



  chat:
 | node_modules:
 | -socket.io
 | -express
 | -log4js
 | -http
 | public:
 | -index.html
 | -socket.io.js
 | - <i> main.css </ i>
 | -main.js
 | chat.js 


Then we make such a “trick” that will send the contents of this folder to the client upon connection:



chat.js:



 app.use(express.static(__dirname + '/public')); //  ""    public   // __dirname -     chat.js 


Great, now when connecting to localhost: 3000 (when the script is running) we will have “index.html” , only the page will be empty because we have “index.html” empty :)



Throw a sketch of the chat in “index.html” (without styles) . You can simply copy the code in "index.html"



 <html> <head> <meta charset="utf-8"> <title>chat</title> <script src="socket.io.js"></script> <script src="https://code.jquery.com/jquery-3.1.0.min.js" charset="utf-8"></script> <script src="main.js" charset="utf-8"></script> <!--     main.css --> </head> <body> <textarea name="name" rows="8" cols="40"></textarea> <p></p> <input type="text" name="text" size="20"> <button type="button" name="button"></button> </body> </html> 


Perfectly! Now if we run the script and open localhost: 3000 , we will see our * curve * sketch) Also, you can see that I connected jQuery, thanks to it we will extract the text from the "convenient" field.



As we can understand, our chat is not working now, as far as the “events” in the script are not configured. Now we will sort everything out. First we need to connect from the client to the server (socket.io) in “main.js”



 var port = 3000; //         var socket = io.connect('http://localhost:' + port); //    "socket" (     )        


Now that we have written the socket.io connection to the server via the port, it’s time to process this event on the server.



io.connect (port) - Creates a 'connection' event, we need to make its handler on the server, otherwise the connection will be * empty *, and we still need to assign a nickname to the one who connected, and this is done in the handler, just read further.



Create a handler in the chat.js script



 io.on('connection', function (socket) { //    'connection'   io.connect(port);   socket var name = 'U' + (socket.id).toString().substr(1,4); //    .    'U'   3  ID ()   ,       '+' socket.broadcast.emit('newUser', name); //   'newUser'  ,  .      'newUser' (      ) socket.emit('userName', name); //     'userName'    (name) (   ) logger.info(name + ' connected to chat!'); //  }); 


So, for those who do not understand ... io.on ('event', function (arg) {}) - creates a wiretap for the event 'event' with an argument arg; we will pass arguments later) socket.id - connection ID of this socket (socket - client) , socket.broadcast.emit ('newUser', name); - sending the 'newUser' event to everyone except the current socket, with the variable name (current socket). socket.emit ('userName', name); - sends the event 'userName' only to the current socket with the variable name.



For those who do not understand - the server and the client can send and receive events in the same way:



socket.emit ('event') - sends to server \ client

socket.on - listens for events on the client

io.on - listens for events on the server



Now we create in "main.js" wiretaps on 'newUser', 'userName' ...



 socket.on('userName', function(userName){ //   'userName'    name    'userName' console.log('You\'r username is => ' + userName); //     $('textarea').val($('textarea').val() + 'You\'r username => ' + userName + '\n'); //            }); socket.on('newUser', function(userName){ //     =) console.log('New user has been connected to chat | ' + userName); //  $('textarea').val($('textarea').val() + userName + ' connected!\n'); //        ,          '  '    }); 


$ ('textarea'). val ('text'); - change the text in the text box. \ n - move to a new line.



Now when we open localhost: 3000 we will see the counter text in the field with our nickname! Perfectly? I know ^^ But agree, this is not a chat yet. Now we need to make sure that when you click on the "Send" <= index.html button, the text is sent to the server. To do this, in "main.js" we add a handler to the button 'button' via jQuery.



 $(document).on('click', 'button', function(){ //     var message = $('input').val(); //          socket.emit('message', message); //   'message'   c   (message)-   $('input').val(null); //     '' }); 


After that, we can safely do the 'message' event handler on the server itself.



chat.js:



 io.on('connection', function (socket) { var name = 'U' + (socket.id).toString().substr(1,4); socket.broadcast.emit('newUser', name); logger.info(name + ' connected to chat!'); socket.emit('userName', name); //   //      socket.on('message', function(msg){ //    'message'   (msg)   message logger.warn('-----------'); // Logging logger.warn('User: ' + name + ' | Message: ' + msg); logger.warn('====> Sending message to other chaters...'); io.sockets.emit('messageToClients', msg, name); //     'messageToClients'       (,  ) }); }); 


Fine! Now when we send the text from the page, it will be logged in the node console, we also sent the event 'messageToClients' to all clients, now we’ll make an event handler on the client ...



main.js:



 socket.on('messageToClients', function(msg, name){ console.log(name + ' | => ' + msg); //     $('textarea').val($('textarea').val() + name + ' : '+ msg +'\n'); //        ( : ) }); 


Our chat is ready! Now you can upgrade it as you like.



This post was created because the topics that were created in Habré to create a chat were posted 5 years ago, and during that time a lot of things happened and I decided to create my own topic) However, here is the topic that I was inspired by - a link . Maybe I was wrong somewhere, correct! All people are wrong.



Thank you all for your attention!

Source: https://habr.com/ru/post/307744/



All Articles