📜 ⬆️ ⬇️

Create a chat on Node.js and Socket.IO

In this article I will try to show how you can create a simple chat using Node.js in conjunction with Socket.IO . Initially, I wanted to build a chat on pure Websockets, but I was faced with the almost complete lack of ready-made server implementations for them on the Internet. So I decided not to reinvent the wheel, but to use the ready-made library.
In my case, the server works under Ubuntu, so all the examples will be for it (and the links in the examples - to him).

Component installation

First of all, we will need the actual Node.js (installation instructions and download links here ) and Socket.IO. Modules for Node.js are easiest to install using the npm manager -
curl http://npmjs.org/install.sh | sh npm install socket.io 

Server part

The structure of the server part is as follows: the server accepts a message, if it is a command — it performs certain actions, if just a message — it sends out to all other participants.
 //       8080- - 80    http- var io = require('socket.io').listen(8080); //     -   production' io.set('log level', 1); //       io.sockets.on('connection', function (socket) { // ..   -       5   ID  var ID = (socket.id).toString().substr(0, 5); var time = (new Date).toLocaleTimeString(); //     ,        socket.json.send({'event': 'connected', 'name': ID, 'time': time}); //    ,        socket.broadcast.json.send({'event': 'userJoined', 'name': ID, 'time': time}); //      socket.on('message', function (msg) { var time = (new Date).toLocaleTimeString(); //  ,        socket.json.send({'event': 'messageSent', 'name': ID, 'text': msg, 'time': time}); //      socket.broadcast.json.send({'event': 'messageReceived', 'name': ID, 'text': msg, 'time': time}) }); //    -   socket.on('disconnect', function() { var time = (new Date).toLocaleTimeString(); io.sockets.json.send({'event': 'userSplit', 'name': ID, 'time': time}); }); }); 

In this code (and a bit more):
io.sockets - select all connected clients
io.sockets.sockets [ID] - selection of a specific customer with id ID
socket - select the "current" client
socket.send (TEXT) - “basic” event, sending a TEXT message
socket.json.send ({}) - send a message in JSON format
socket.broadcast.send - send a message to all clients except the current one
socket.emit (EVENT, JSON) - sending a custom EVENT event with JSON data (for example - socket.emit ('whereami', {'location': loc})), can be used to rewrite the standard 'connected', 'message' events and 'disconnect'.
socket.on (EVENT, CALLBACK) - a call to the CALLBACK function when an EVENT event occurs (for example, socket.on ('whereami', function (loc) {console.log ('I \' m in '+ loc +'! ') ;}))
I send messages to clients in JSON, because the message text itself is automatically generated in the client. Thus, the presentation of the data does not depend on the server and it is easy to change it without touching it (for example, changing the language); moreover, a smaller amount of data is transmitted between the server and the client.

Client part

HTML and CSS

index.html:
 <!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <link href="style.css" rel="stylesheet"> <script src="http://46.182.31.65:8080/socket.io/socket.io.js"></script> <script src="client.js"></script> </head> <body> <div id="log"></div><br> <input type="text" id="input" autofocus><input type="submit" id="send" value="Send"> </body> </html> 

style.css
 #log { width: 590px; height: 290px; border: 1px solid rgb(192, 192, 192); padding: 5px; margin-bottom: 5px; font: 11pt 'Palatino Linotype'; overflow: auto; } #input { width: 550px; } #send { width: 50px; } .in { color: rgb(0, 0, 0); } .out { color: rgb(0, 0, 0); } .time { color: rgb(144, 144, 144); font: 10pt 'Courier New'; } .system { color: rgb(165, 42, 42); } .user { color: rgb(25, 25, 112); } 

Javascript

socket.io.js is automatically given to Node.js at nodeJsIp [: port] /socket.io/socket.io.js - you don’t need to do anything else.
client.js
 //      strings = { 'connected': '[sys][time]%time%[/time]:       [user]%name%[/user].[/sys]', 'userJoined': '[sys][time]%time%[/time]:  [user]%name%[/user]   .[/sys]', 'messageSent': '[out][time]%time%[/time]: [user]%name%[/user]: %text%[/out]', 'messageReceived': '[in][time]%time%[/time]: [user]%name%[/user]: %text%[/in]', 'userSplit': '[sys][time]%time%[/time]:  [user]%name%[/user]  .[/sys]' }; window.onload = function() { //    ; websockets -    ,  xhr if (navigator.userAgent.toLowerCase().indexOf('chrome') != -1) { socket = io.connect('http://46.182.31.65:8080', {'transports': ['xhr-polling']}); } else { socket = io.connect('http://46.182.31.65:8080'); } socket.on('connect', function () { socket.on('message', function (msg) { //    ,  ,      document.querySelector('#log').innerHTML += strings[msg.event].replace(/\[([az]+)\]/g, '<span class="$1">').replace(/\[\/[az]+\]/g, '</span>').replace(/\%time\%/, msg.time).replace(/\%name\%/, msg.name).replace(/\%text\%/, unescape(msg.text).replace('<', '&lt;').replace('>', '&gt;')) + '<br>'; //     document.querySelector('#log').scrollTop = document.querySelector('#log').scrollHeight; }); //   <Enter>     document.querySelector('#input').onkeypress = function(e) { if (e.which == '13') { //   input',   escape- socket.send(escape(document.querySelector('#input').value)); //  input document.querySelector('#input').value = ''; } }; document.querySelector('#send').onclick = function() { socket.send(escape(document.querySelector('#input').value)); document.querySelector('#input').value = ''; }; }); }; 

')
Finally, we start the server with the log in the file and in the background -
 node server.js > output.log & 

(It should be noted that the script was launched only from the user directory where node.js was placed)

All sources can be downloaded here . Immediately I say, I am not a programming guru and wrote for myself, so I ask you not to swear at the sloppy (and it is useless). Because Apache gives while statics, it is desirable to run on your computer. If laziness or uncomfortable / can not - a live example can be found here .

The code has been tested and works in Opera 11+, Firefox 5+, Chrome 12+. IE9 judging by the logs connects, receives and sends packets, but this is not reflected on the browser.

Used materials:
socket.io/#how-to-use
github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
google.com

In the next issue: we write down the history of messages, change our name for ourselves, write to another player in private, and much more!

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


All Articles