Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a real-time chat program with Node.js + Web Socket

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use Node.js + Web Socket to create a live chat program". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Source code & demonstration

Online demo (the network speed of heroku server is a little slow and the free package is a small water pipe, it is recommended to download the code and run locally)

The source code can be downloaded from the GitHub page of the project.

Local operation method:

Run npm install on the command line

After the module is downloaded successfully, run node server to start the server

Open a browser to access localhost

The following is a preview of the effect:

Preparatory work

The example environment of this article is Windows,Linux, but the installation of Node is slightly different from the command line, and the implementation part of the program has nothing to do with the platform.

Node correlation

You need to install Node.js on this machine (nonsense)

You need some basic knowledge of Node.js. If you haven't already learned about Node.js, here's a good tutorial for getting started.

Then we can start creating a simple HTTP server.

Similar to the very simple code below, it creates a HTTP server and listens to port 80 of the system.

/ / node server example

/ / introduce http module var http = require ('http'), / / create a server server = http.createServer (function (req, res) {res.writeHead (200,{' Content-Type': 'text/plain'}); res.write (' hello worldview'); res.end ();}) / / listen for port 80 server.listen (80); console.log ('server started')

Save it as a js file such as server.js, and then run node server or node server.js from the command line, and the server can be started. At this time, we can enter localhost or native IP127.0.0.1 in the browser address bar, without adding a port, because our server is listening on the default port 80. Of course, if port 80 on your machine is occupied by other programs, you can choose another port, such as 8080, so you need to add the port number localhost:8080 when you access it.

Express

First install through npm

Open the command line under our project folder (tip: hold down Shift and right-click, you can find the 'Open Command Line from here' option in the right-click menu)

Enter npm install express enter on the command line to install

Then introduce it into the project through require ('express') in server.js for use

Express is a module in node.js that manages routing response requests and returns the corresponding HTML page according to the requested URL. Here we use a pre-written static page to return to the client, just use express to specify the path of the page to be returned. If we don't use this package, we need to write the HTML code with the background JavaScript code to respond to the request, which is not convenient.

/ / return a simple HTML content

Server = http.createServer (function (req, res) {res.writeHead (200,{ 'Content-Type':' text/html' / / change the return type from text/plain to text/html}); res.write ('hello worldview'); / / return HTML tag res.end ();})

In the place where the server.js file created in the previous step is stored, we create a new folder named www to store our web files, including images and front-end js files. Assuming that you have written an index.html file under the www folder (described in the next step, you can put an empty HTML file), you can use express to return the page to the browser in the following ways. As you can see from the beginning, our server code is a lot simpler.

/ / use express module to return static page

Var express = require ('express'), / / introduce the express module app = express (), server = require (' http') .createServer (app); app.use ('/', express.static (_ _ dirname +'/ www')); / / specify the location of the static HTML file server.listen (80)

There are four buttons, which are setting font color, sending emoticons, sending pictures and clearing records, which will be described below.

Socket.io

A package that uses socket in Node.js. Using it, you can easily establish a sockets connection from the server to the client, send events and receive specific events.

Npm install socket.io is also installed through npm. After installation, a new socket.io folder is generated under the node_modules folder, in which we can find a socket.io.js file. Introduce it to the HTML page so that we can use socket.io to communicate with the server at the front end.

At the same time, server.js on the server side is the same as using express, and it is also introduced into the project through require ('socket.io'), so that socket.io can be used on the server side.

With socket.io, the front and back end syntax is consistent, that is, an event is fired by socket.emit (), and the corresponding event is listened for and processed by socket.on (). The two events communicate through the passed parameters. The specific working mode can be seen in the following example.

For example, we have the following JavaScript code in index.html (suppose you have put a button with ID as sendBtn on the page):

Var socket=io.connect (), / / connect to the server button=document.getElementById ('sendBtn'); button.onclick=function () {socket.emit (' foo', 'hello'); / / send an event named foo and pass a string data' hello'}

The above code first establishes a connection to the server, and then gets an instance of socket. Then if a button with ID sendBtn on the page is clicked, we initiate an event called foo through this socket instance, passing a hello string message to the server.

At the same time, we need to write code on the server side to handle the foo event and receive the passed data.

To do this, we can write this in server.js:

/ var express = require ('express'), app = express (), server = require (' http') .CreateServer (app), io = require ('socket.io') .response (server); / / introduce socket.io module and bind to server app.use (' /', express.static (_ _ dirname +'/ www')); server.listen (80) / / socket partial io.on ('connection', function (socket) {/ / receive and process the foo event socket.on sent by the client (' foo', function (data) {/ / output messages to the console console.log (data);})})

Now that Ctrl+C shuts down the server that started before, type node server to start the server again and run the new code to see the effect. If everything is all right, you will see the output 'hello' string in the command line window after clicking the button on the page.

As mentioned earlier, the syntax of socket.io is consistent at the front and back end, so on the contrary, it is obvious that events are sent from the server to the client, where messages are received and processed on the client side. This is just a brief introduction, which will be further introduced by sending chat messages below.

Basic page

With some of the above basic understanding, you can enter the development of chat program functions.

First, let's build the main page. Because it is a more popular application, there is no need to think about the interface. There is already a rough prototype in mind. It has a main form to present messages, a text box to input messages, and a button to send messages. These three are necessary.

In addition, we are going to implement the following four functions, so there are also four buttons on the interface to set font color, send emoticons, send pictures and clear records.

The last page is the one shown in the previous screenshot, and the code is as follows:

Www/index.html

Hichat HiChat:) Connecting to server...

Style file www/styles/main.css

Html, body {margin: 0; background-color: # efefef; font-family: sans-serif;} .wrapper {width: 500px; height: 640px; padding: 5px; margin: 0 auto; background-color: # ddd;} # loginWrapper {position: fixed; top: 0; right: 0; bottom: 0; left: 0 Background-color: rgba (5, 5, 5, .6); text-align: center; color: # fff; display: block; padding-top: 200px;} # nickWrapper {display: none;} .banner {height: 80px; width: 100%;} .banner p {float: left; display: inline-block;} .controls {height: 100px; margin: 5px 0px Position: relative;} # historyMsg {height: 400px; background-color: # fff; overflow: auto; padding: 2px;} # historyMsg img {max-width: 99%;} .timespan {color: # ddd;} .items {height: 30px;} # colorStyle {width: 50px; border: none; padding: 0 } / * custom the file input*/ .imageLable {position: relative;} # sendImage {position: absolute; width: 52px; left: 0; opacity: 0; overflow: hidden;} / * end custom file input*/ # messageInput {width: 440px; max-width: 440px; height: 90px; max-height: 90px;} # sendBtn {width: 50px; height: 96px Float: right;} # emojiWrapper {display: none; width: 500px; bottom: 105px; position: absolute; background-color: # aaa; box-shadow: 00 10px # 555;} # emojiWrapper img {margin: 2px; padding: 2px; width: 25px; height: 25px;} # emojiWrapper img:hover {background-color: blue;} .emoji {display: inline } footer {text-align: center;}

In order to make the project have a good directory structure to facilitate management, here under the www folder created a new styles folder to store the style file main.css, and then create a new scripts folder to store front-end js files such as hichat.js (we front-end all the js code will be placed in this file), while our server js file server.js location remains unchanged or placed on the outermost layer.

At the same time, create a new content folder to store other resources such as pictures, etc., and create an emoji folder in the content folder to store emoji gif images, which will be used later. Finally, the directory structure of our project should look like this:

├─ node_modules └─ www ├─ content │ └─ emoji ├─ scripts └─ styles

What you see when you open the page is a light black mask layer, and the next thing we need to do is to enter the user's nickname and log in to the server. This mask layer is used to display status information about the connection to the server, and when the connection is complete, an input box appears for nickname input.

As you can see in the above HTML code, we have introduced the www/scripts/hichat.js file to the page, so let's start to write some basic front-end js to implement the connection function.

Define a global variable for the development HiChat of our entire program, and use _ window.onload to instantiate HiChat after the page is ready and call its init method to run our program.

Www/scripts/Hichat.js

_ window.onload = function () {/ / instance and initialize our hichat program var hichat = new HiChat (); hichat.init ();}; / / define our hichat class var HiChat = function () {this.socket = null;}; / / add business methods HiChat.prototype = {init: function () {/ / this method initializer var that = this to the prototype / / establish a socket connection to the server this.socket = io.connect (); / / listen to the connect event of socket, which indicates that the connection has been established this.socket.on ('connect', function () {/ / after connecting to the server, display the nickname input box document.getElementById (' info'). TextContent = 'get yourself a nickname:)' Document.getElementById ('nickWrapper'). Style.display =' block'; document.getElementById ('nicknameInput'). Focus ();});}}

The above code defines the class HiChat that the entire program needs to use, and then all the business logic such as processing messages and displaying messages is written in this class.

First of all, a program initialization method is defined, which initializes socket, listens for connection events, and displays a nickname input box once connected to the server. When the user enters the nickname, it can be received in the server background and processed in the next step.

Set nickname

We require connected users to set up a nickname first, and the nickname should be unique, that is, it cannot have the same name as others. One is to make it easy for users to distinguish, the other is to count the number of people online, and it is also convenient to maintain an array of nicknames for all users.

To do this, in the background server.js, we create a global array variable called users, which presses the nickname into the users array when a user sets the nickname to send to the server. At the same time, note that if the user is disconnected, it should be removed from the users array accordingly to ensure the correctness of the data.

In the foreground, after typing the nickname and clicking OK submit, we need to initiate an event that sets the nickname so that the server can hear it. Add the following code to the previous init method.

Www/scripts/hichat.js

/ / the confirm button for nickname settings document.getElementById ('loginBtn') .addEventListener (' click', function () {var nickName = document.getElementById ('nicknameInput') .value) / / check whether the nickname input box is empty if (nickName.trim (). Length! = 0) {/ / is not empty, then raise a login event and send the entered nickname to the server that.socket.emit ('login', nickName);} else {/ / otherwise the input box gets the focus document.getElementById (' nicknameInput'). Focus ();} }, false)

Server.js

/ var express = require ('express'), app = express (), server = require (' http') .createServer (app), io = require ('socket.io') .createServer (server), users= []; / / keep the nickname app.use (' /', express.static (_ _ dirname +'/ www')) of all online users; server.listen (80) / / socket partial io.on ('connection', function (socket) {/ / nickname setting socket.on (' login', function (nickname) {if (users.indexOf (nickname) >-1) {socket.emit ('nickExisted');} else {socket.userIndex = users.length; socket.nickname = nickname; users.push (nickname)) Socket.emit ('loginSuccess'); io.sockets.emit (' system', nickname); / / send the nickname of the currently logged-in user to all clients connected to the server};}); it should be explained that in the callback function of the connection event, socket represents the client that is currently connected to the server. So the code socket.emit ('foo') only receives the event itself, while socket.broadcast.emit (' foo') means to send the event to everyone except yourself. In addition, in the above code, io represents the entire socket connection to the server, so the code io.sockets.emit ('foo') means that everyone can receive the event.

The above code first determines whether the received nickname already exists in the users, and if so, sends itself a nickExisted event, and after the front end receives this event, we display a message to notify the user.

Add the following code to the inti method of hichat.js.

Www/scripts/hichat.js

This.socket.on ('nickExisted', function () {document.getElementById (' info'). TextContent ='! nickname is taken, choose another pls'; / / hint that the nickname is occupied})

If the nickname is not occupied by another user, press the nickname into the users array, save it as an attribute in the current socket variable, and save the user's index in the array (because it is the last element of the array, so the index is the length users.length of the array) into socket as an attribute, which will be used later. Finally, send yourself a loginSuccess event to notify the front end of a successful login. After receiving the success message, the front end removes the gray mask layer to display the chat interface.

Add the following code to the inti method of hichat.js.

Www/scripts/hichat.js

This.socket.on ('loginSuccess', function () {document.title =' hichat |'+ document.getElementById ('nicknameInput'). Value; document.getElementById (' loginWrapper'). Style.display = 'none';// Hidden Mask layer shows chat interface document.getElementById (' messageInput'). Focus (); / / Let the message input box get focus}); online statistics

Here, it is realized to display the number of online users and to display the user connection departure in the chat main interface as a system.

In addition to the loginSuccess event in the above server.js, there is a code that sends a system event to all users through io.sockets.emit, passing the nickname of the user who has just logged in. When everyone receives this event, a system message "so-and-so has joined the chat room" will be displayed in the chat window. At the same time, considering that we don't know whether the user is entering or leaving at the front end, we pass one more data in this system event to indicate whether the user is entering or leaving.

Change the login event in server.js as follows:

Server.js

Socket.on ('login', function (nickname) {if (users.indexOf (nickname) >-1) {socket.emit (' nickExisted');} else {socket.userIndex = users.length; socket.nickname = nickname; users.push (nickname); socket.emit ('loginSuccess'); io.sockets.emit (' system', nickname, users.length, 'login') };)

One more login string is passed than before.

At the same time, add an event that the user leaves, which may be done through the disconnect event that comes with socket.io. When a user is disconnected, the disconnect event will be triggered. In this event, you do two things, one is to remove the user from the users array, and the other is to send a system event notifying everyone that'so-and-so has left the chat room'.

Add the following code to the callback function of connection in server.js.

Server.js

/ / disconnected event socket.on ('disconnect', function () {/ / removes the disconnected user from the users (socket.userIndex, 1); / / notifies everyone except yourself of socket.broadcast.emit (' system', socket.nickname, users.length, 'logout');})

The above code removes the currently disconnected user from the users array through the splice method of the JavaScript array, and here we see that the previously saved user index is used. At the same time, send the same system event as when the user connects to notify everyone that "so-and-so has left". In order to let the front end know that it is a departure event, a 'logout' string is sent.

Let's start with the front-end implementation, that is, receiving system events.

In hichat.js, add the following code to the init method.

Www/scripts/hichat.js

This.socket.on ('system', function (nickName, userCount, type) {/ / determine whether the user connects or leaves to display different information var msg = nickName + (type = =' login'?' Joined': 'left'); var p = document.createElement (' p'); p.textContent = msg; document.getElementById ('historyMsg') .appendChild (p); / / display the number of people online to the top of the page document.getElementById (' status'). TextContent = userCount + (userCount > 1?' Users': 'user') +' online';})

Now run the program, open multiple browser tabs, then log in and leave, and you can see the corresponding system prompt message.

Send a message

User connection and disconnection we need to display system messages, users also frequently send chat messages, so we can consider displaying the message to the page to write a separate function to facilitate us to call. To do this, we add a _ displayNewMsg method to the HiChat class, which receives three parameters: the message to be displayed, who the message comes from, and a color. Because we want system messages to be different from those of ordinary users, we add a color parameter. At the same time, this parameter is also convenient for us to later implement to allow users to customize the text color to prepare.

Add the following code to my HiChat class.

Www/scripts/hichat.js

/ / add business methods HiChat.prototype = {init: function () {/ / this method initializer / /...}, _ displayNewMsg: function (user, msg, color) {var container = document.getElementById ('historyMsg'), msgToDisplay = document.createElement (' p'), date = new Date (). ToTimeString (). Substr (0,8) MsgToDisplay.style.color = color | |'# 000mm; msgToDisplay [XSS _ clean] = user +'('+ date +'):'+ msg; container.appendChild (msgToDisplay); container.scrollTop = container.scrollHeight;}}

In the _ displayNewMsg method, we also add a date to the message. We also determine whether the method passes a color parameter when it is called, and if it does not pass a color, the default is # 000, that is, black.

At the same time, modify our code that displays the system message in the system event to call the _ displayNewMsg method.

Www/scripts/hichat.js

This.socket.on ('system', function (nickName, userCount, type) {var msg = nickName + (type = =' login'?' Joined': 'left'); / / specifies that the system message is displayed in red that._displayNewMsg (' system', msg, 'red'); document.getElementById (' status'). TextContent = userCount + (userCount > 1?' Users': 'user') +' online';})

The effect now is as follows:

With this method of displaying messages, we begin to implement the chat function between users.

The practice is also very simple, if you have mastered the emit sending events and on receiving events described above, then you will be familiar with sending and receiving user chat messages.

First of all, write a click event handler for the send button on the page, we use addEventListner to listen for this click event, when the user clicks send, first check whether the input box is empty, if not, then send the postMsg event to the server, send the chat text entered by the user to the server, receive and distribute it to all users except themselves.

Add the following code to the inti method of hichat.js.

Www/scripts/hichat.js

Document.getElementById ('sendBtn') .addEventListener (' click', function () {var messageInput = document.getElementById ('messageInput'), msg = messageInput.value; messageInput.value =''; messageInput.focus (); if (msg.trim (). Length! = 0) {that.socket.emit ('postMsg', msg); / / send the message to the server that._displayNewMsg (' me', msg) / / display your messages in your own window};}, false)

Add code in server.js to receive the postMsg event.

Server.js

Io.on ('connection', function (socket) {/ / other code. / / receive a new message socket.on ('postMsg', function (msg) {/ / send the message to all users except yourself socket.broadcast.emit (' newMsg', socket.nickname, msg);});})

Then the newMsg event sent by the server is received on the client side and the chat message is displayed to the page.

The following code display has been added to the init method of hichat.js.

This.socket.on ('newMsg', function (user, msg) {that._displayNewMsg (user, msg);})

Run the program and now you can send chat messages.

Send a picture

The above has achieved the basic chat function, further, if we want to allow users to send pictures, then the program will be even more perfect.

The picture is different from the text, but by converting the picture to a string, you can send the picture like a plain text message, but restore it to the picture when displayed.

Before that, we have put the picture button on the page, which is actually a file type of input, and we just need to do some work on it.

After the user clicks the picture button, a file selection window pops up for the user to select the picture. We can then use FileReader in the JavaScript code to read the picture as a string in base64 format and send it. The picture in base64 format can be directly specified as the src of the picture, so that the picture can be displayed on the page with an img tag.

To do this, we listen to the change event of the picture button. Once the user has selected the picture, it will be displayed on their own screen and read as text and sent to the server.

Add the following code to the init method of hichat.js.

Www/scripts/hichat.js

Document.getElementById ('sendImage') .addEventListener (' change', function () {/ / check whether a file is selected if (this.files.length! = 0) {/ / get the file and read it with FileReader var file = this.files [0], reader = new FileReader () If (! reader) {that._displayNewMsg ('system','! your browser doesn\'t support fileReader', 'red'); this.value =''; return;} Reader.onload = function (e) {/ / read successfully, displayed to the page and sent to the server this.value ='; that.socket.emit ('img', e.target.result); that._displayImage (' me', e.target.result);}; reader.readAsDataURL (file);} }, false)

After the above image is successfully read, the _ displayNImage method is called to display the image on its own screen and an img event is sent to the server. In server.js, we use this event to receive and distribute the image to each user. At the same time, it also means that we have to write the corresponding code at the front end to receive.

This _ displayNImage has not been implemented yet and will be described below.

Add the following code to the socket callback function of server.js.

Server.js

/ / receive the picture socket.on sent by the user ('img', function (imgData) {/ / distribute to each user except yourself through a newImg event socket.broadcast.emit (' newImg', socket.nickname, imgData);})

At the same time, add the following code to the init method of hichat.js to receive the display picture.

This.socket.on ('newImg', function (user, img) {that._displayImage (user, img);})

One problem is that if the picture is too large, it will destroy the layout of the entire window, or a horizontal scroll bar will appear, so we style the picture so that it can only be displayed at most 99% of the width of the chat window. in this way, too large pictures will shrink themselves.

# historyMsg img {max-width: 99%;}

But considering that the reduced image may be distorted and the user can't see it clearly, we need to provide a way for the user to view the original size picture, so wrap the picture with a link. When we click on the picture, we open a new window page and present the picture to the new page according to the original size for the user to view.

So in the end, the _ displayNImage method we implemented should look like this.

Add the following code to the HiChat class of hichat.js.

Www/scripts/hichat.js

_ displayImage: function (user, imgData, color) {var container = document.getElementById ('historyMsg'), msgToDisplay = document.createElement (' p'), date = new Date (). ToTimeString (). Substr (0,8); msgToDisplay.style.color = color | |'# 000yuan; msgToDisplay [XSS _ clean] = user +'('+ date +'):'+'

'; container.appendChild (msgToDisplay); container.scrollTop = container.scrollHeight;}

Start the server to open the program again, and we can send pictures.

Send facial expressions

It is always difficult for words to express the facial expression when speaking, so the expression is born.

I've already introduced how to send a picture. Strictly speaking, an expression is also a picture, but it has something special because it can be interspersed with text, so you can't deal with it like you do with a picture.

According to past experience, other chat programs convert emoticons into symbols. For example, I want to send a smiley face, and stipulate that the symbol':) 'code smiley facial expressions, and then in the process of data transmission, what is actually transferred is a combination of colons and closing parentheses. When each client receives the message, the emoticons are extracted from the text and replaced with gif images. When presented to the page in this way, we can see the mixed arrangement of expressions and words.

Hello, emoji:23 [Nima]-> Hello, Nima Wang

The above vividly shows the use of expressions in our program, and you can see that I specify a format to represent expressions, [emoji:xx], enclosed in parentheses and then 'emoji' with a colon followed by a number that represents the number of a gif picture. In the program, if we click the emoji button and then present all the available emoji images, when the user selects an emoji, the corresponding code is generated and inserted into the current text message to be sent. After sending it out, everyone receives a message in the form of a code, but after displaying the message in front of the page, we extract the expression code, get the picture number, and replace it with the corresponding picture.

First of all, you have to display all the available emoticons in a small window, which will be displayed after clicking the emoji button, which is already added to the HTML code, and you only need to implement the code.

We use Tuzki as the meme of our chat program. As you can see, there are a lot of gif diagrams, and if you write them manually, it takes some effort to keep writing.

So consider leaving this work to the code to automate and write a method to initialize all emoticons

To do this, add the following code to the HiChat class and call this method in the init method.

Www/scripts/hichat.js

_ initialEmoji: function () {var emojiContainer = document.getElementById ('emojiWrapper'), docFragment = document.createDocumentFragment (); for (var I = 69; I > 0; iMurray -) {var emojiItem = document.createElement (' img'); emojiItem.src ='.. / content/emoji/' + I + '.gif'; emojiItem.title = I; docFragment.appendChild (emojiItem);} EmojiContainer.appendChild (docFragment);}

Also add the following code to the init method of hichat.js.

Www/scripts/hichat.js

This._initialEmoji (); document.getElementById ('emoji'). AddEventListener (' click', function (e) {var emojiwrapper = document.getElementById ('emojiWrapper'); emojiwrapper.style.display =' block'; e.stopPropagation ();}, false); document.body.addEventListener ('click', function (e) {var emojiwrapper = document.getElementById (' emojiWrapper')) If (e.target! = emojiwrapper) {emojiwrapper.style.display = 'none';};})

Two click events have been added to the page, one is to click the emoji button to display the emoji window, and the other is to click elsewhere on the page to close the emoji window.

What we need to do now is that after a certain expression is selected, we need to get the selected expression, and then convert it to the corresponding expression code and insert it into the message box.

To do this, let's write another click event handler for these images. Add the following code to the inti method of hichat.js.

Www/scripts/hichat.js

Document.getElementById ('emojiWrapper') .addEventListener (' click', function (e) {/ / get the clicked emoji var target = e.target; if (target.nodeName.toLowerCase () = = 'img') {var messageInput = document.getElementById (' messageInput'); messageInput.focus (); messageInput.value = messageInput.value +'[emoji:' + target.title +']';};}, false)

Now that the emoji is selected, you can get the corresponding code in the message input box.

After sending, there is no difference between ordinary message sending, because the text message has been sent before, so there is no need to implement anything here, but we just need to change the code we used to display the message before. First, determine whether the message text contains emoji, if so, convert it to a picture, and then display it to the page.

For this reason, we write a method to receive a text message as a parameter, use a regular search for the emoji in it, replace it with an img tag, and finally return the processed text message.

Add the following code to the HiChat class.

Www/scripts/hichat.js

_ showEmoji: function (msg) {var match, result = msg, reg = /\ [emoji:\ d +\] / g, emojiIndex, totalEmojiNum = document.getElementById ('emojiWrapper'). Children.length; while (match = reg.exec (msg)) {emojiIndex = match [0] .slice (7,-1) If (emojiIndex > totalEmojiNum) {result = result.replace (match [0],'[X]');} else {result = result.replace (match [0],'

');}; return result;}

Now let's modify the _ displayNewMsg method of the message before we display it so that it calls the _ showEmoji method before displaying the message.

_ displayNewMsg: function (user, msg, color) {var container = document.getElementById ('historyMsg'), msgToDisplay = document.createElement (' p'), date = new Date (). ToTimeString (). Substr (0,8), / / convert the facial expressions in the message to pictures msg = this._showEmoji (msg); msgToDisplay.style.color = color | |'# 000' MsgToDisplay [XSS _ clean] = user +'('+ date +'):'+ msg; container.appendChild (msgToDisplay); container.scrollTop = container.scrollHeight;}

The following is the effect of the implementation:

The main functions have been almost completed, in order to make the program more humane and beautiful, you can add a function to modify the text color, as well as keyboard shortcut operation support, which is also the function of general chat programs. Enter can send a message.

Text color

Fortunately, HTML5 has added a new input tab for color selection, and Chrome's support for it is so great that it pops up directly in the system's color pickup window.

IE and FF are a common text box, but it does not affect the use, but the user can only enter specific color values to set the color, which is not as convenient and intuitive as in Chrome.

Previously, our _ displayNewMsg method could receive a color parameter, but now all we have to do is add an extra color parameter every time a message is sent to the server, and pass this color when the message is called _ displayNewMsg.

The following is an example of modifying the code of the message sending button in hichat.js:

Document.getElementById ('sendBtn') .addEventListener (' click', function () {var messageInput = document.getElementById ('messageInput'), msg = messageInput.value, / / get the color value color = document.getElementById (' colorStyle'). Value; messageInput.value ='; messageInput.focus () If (msg.trim (). Length! = 0) {/ / display and send with color value parameters that.socket.emit ('postMsg', msg, color); that._displayNewMsg (' me', msg, color);};}, false)

At the same time, modify the code that receives the message in the hichat.js to receive the color value.

This.socket.on ('newMsg', function (user, msg, color) {that._displayNewMsg (user, msg, color);})

This only shows the modification of the send button, the change is very small, just get the color value each time the message is sent, and the emit event also takes this color value to the server, so that the front end can display the color set for each user according to this color value. The rest is to add color to the picture in the same way, which is omitted here.

Final effect:

Key operation

Add the following code to the inti method of hichat.js so that after entering the nickname, press enter to log in, and enter to send a message after entering the chat interface.

Document.getElementById ('nicknameInput') .addEventListener (' keyup', function (e) {if (e.keyCode = = 13) {var nickName = document.getElementById ('nicknameInput'). Value; if (nickName.trim (). Length! = 0) {that.socket.emit (' login', nickName);}, false) Document.getElementById ('messageInput'). AddEventListener (' keyup', function (e) {var messageInput = document.getElementById ('messageInput'), msg = messageInput.value, color = document.getElementById (' colorStyle'). Value; if (e.keyCode = = 13 & & msg.trim (). Length! = 0) {messageInput.value ='; that.socket.emit ('postMsg', msg, color) That._displayNewMsg ('me', msg, color);};}, false); deployment online

The final step, of course, is to deploy our hard work to the actual site. This should be the most exciting and relieved moment. But before that, let's add a common package.json file for node.js programs, which can specify which modules our program uses, so that after others get the code, they can download the modules needed in the installer by themselves through the npm install command, instead of having to release the modules with the source code.

Add a package.json file

Save the following code as package.json to the same location as server.js.

{"name": "hichat", "description": "a realtime chat web application", "version": "0.4.0", "main": "server.js", "dependencies": {"express": "3.4.x", "socket.io": "0.9.x"} "engines": {"node": "0.10.x", "npm": "1.2.x"}} Cloud service selection and deployment

First of all, we have to choose a CVM that supports Node.js and web socket protocol as well. Because it's just for testing, it doesn't matter about space and memory limits, as long as it's free. Node.js lists many CVMs that support Node.js environment on the Wiki page of GitHub, and only heroku is selected to meet the criteria.

If you have deployed relevant Node programs to heroku before, you must know the trouble, and if you make a mistake, it is not easy to debug. But when I was writing this blog, I found a sharp tool codeship. After binding it to your github, every time you submit new code, it will be automatically deployed to heroku. Don't do anything!

Code updates, environment settings, compilation and deployment are all done automatically, and detailed log information and status information of each step are provided. The method of use is also very simple, after registration, press the prompt, two or three steps to complete, in view of this article is long enough, should be a record, here will not say much.

Known problem

After deployment and testing, we found some problems that did not occur locally, mainly as follows:

The first time the connection is too slow, sometimes it fails and 503 errors occur. After looking up the heroku document, the official said that the program will be very slow due to resource constraints when it is connected for the first time. This is the result that the free package is destined to be despised, but it can be tolerated for online testing.

When sending emoticons, Chrome will re-request gif images that have been downloaded to the client to the server, but IE and FF do not have this problem, resulting in delay in facial expressions in Chrome, which leads to the phenomenon that the main message window of the chat is not scrolled in time.

The user will lose contact with the server after being inactive for a certain period of time, and the socket will be disconnected automatically. I don't know if it is the internal mechanism of socket.io or heroku again.

This is the end of the content of "how to create a live chat program with Node.js + Web Socket". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report