The Code word is not easy, the helpful students hope to pay attention to my wechat public number: Code program life, thank you! Code for your own use.

WebSocket is also a very important technology stack on the front end.

All kinds of websites, apps and widgets now come with instant messaging capabilities. The main application of WebSocket is instant messaging.

WebSocket is very, very extensive and very detailed on the web, so I won’t go into it too much.

The appearance of WebSocket solved the ancient “ugly” of HTTP polling.

This video uses native JavaScript+ NodeJS to implement a basic chat room function.

I’ll start with a directory file:

The front-end content is stored in chat folder, consisting of two pages, entry. HTML and index.html. The back-end content is stored in server folder, and the main logic is written in index.js.

Front end:

Entry. HTML content:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="username"  placeholder="Please enter user name"/>
    <button id="enter">Enter a chat room</button>
    <script>; ((doc,storage,location) = > {
            const oUsername = doc.querySelector('#username');
            const oEnterBtn = doc.querySelector('#enter');

            const init = () = > {
                bindEvent(); 
            }

            function bindEvent(){
                oEnterBtn.addEventListener('click',handleEnterBtnClick,false);
            }
            function handleEnterBtnClick(){
                const username = oUsername.value.trim();
                console.log(username);
                if(username.length < 6){
                    alert('Username must be no less than 6 characters');
                    return;
                }
                storage.setItem('username',username);
                location.href = 'index.html'; } init(); }) (document.localStorage,location);
    </script>
</body>
</html>
Copy the code

This page is mainly to do a login, do a little rough, did not write UI, mainly to store a localStorage for the next page communication.

Index.html content:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial =1.0"> <title>Document</title> </head> <body> <ul id="list"> <input type="text" id="message" Placeholder =" input message "/> <button id="send"> </button> </ul> <script> const oList = document.querySelector('#list'); const oMessage = document.querySelector('#message'); const oSendBtn = document.querySelector('#send'); let username = ''; const ws = new WebSocket('ws:localhost:8000'); oSendBtn.addEventListener('click',handleSendBtnClick,false); ws.addEventListener('open',handleOpen,false); ws.addEventListener('close',handleClose,false); ws.addEventListener('error',handleError,false); ws.addEventListener('message',handleMessage,false); function handleSendBtnClick(){ console.log('send message'); const msg = oMessage.value; if(! msg.trim().length){ return; } ws.send(JSON.stringify({ user:username, dateTime:new Date().getTime(), message:msg })) oMessage.value = ''; } function handleOpen(){ console.log('WebSocket open'); username = localStorage.getItem('username'); if(! username){ location.href = 'entry.html'; return; } } function handleClose(){ console.log('WebSocket close'); } function handleError(){ console.log('WebSocket error'); } function handleMessage(e){ console.log('WebSocket message'); console.log(e); const msgData = JSON.parse(e.data); oList.appendChild(createMsg(msgData)); } function createMsg(data){ const {user,dateTime,message} = data; const oItem = document.createElement('li'); OItem. InnerHTML = ` < p > < span > ${user} < / span > < I > ${new Date (dateTime)} < / I > < / p > < p > message: ${message} < / p > ` return oItem; } </script> </body> </html>Copy the code

This page is the content of the chat room, accompanied by a lot of DOM manipulation, may be a bit messy, I also did not divide modules, all written together, easy to copy and paste.

In fact, the front-end part mainly instantiates a WebSocket object, whether front-end or back-end, WebSocket is an event-driven way to exist.

The main front-end events are Open, Close, Error, and Message.

The functions of Open, close and error are the same as their names without much explanation.

The main event is the Message event, which receives messages pushed from the back end.

The backend part

Install the WS module before writing the backend, open the console for input

npm i ws -s
Copy the code

index.js

const ws = require('ws'); ; ((ws) = >{
    const server = new ws.Server({port:8000});
    const init = () = > {
        bindEvent();
    }

    function bindEvent() {
        server.on('open',handleOpen);
        server.on('close',handleClose);
        server.on('error',handleError);
        server.on('connection',handleConnection);
    }
    function handleOpen(){
        console.log('WebSocket open');
    }
    function handleClose(){
        console.log('WebSocket close');
    }
    function handleError(){
        console.log('WebSocket error');
    }
    function handleConnection(ws){
        console.log('WebSocket connection');
        ws.on('message',handleMessage);
    }
    function handleMessage(msg){
        console.log('WebSocket message');
        console.log(msg);
        server.clients.forEach(function(c){
            c.send(msg);
        })
    }
    init();
})(ws);
Copy the code

The backend uses NodeJS and is also event-driven.

The main events are: Open, close, Error, Message, connection the first three events are still the name.

The Message event is stored in the parameter of the Connection event, so bind the Message event to the Connection.

Connection is an event that indicates whether communication has been successfully connected.

The argument to Message is the message passed from the front end. Then all you have to do is distribute the received front-end information to everyone in the chat room.

At the top of the code, we instantiate the Server object for a WS module. The Server object has a Clients property on which all users logged into the chat room are mounted. So we just need the forEach loop to distribute the received front-end information to everyone.

In fact, so far we have completed a most basic WebSocket technology based on native JavaScript implementation of the chat room.

I opened a Chrome browser and a UC browser.

Let’s take a look at the effect:

Without any problems, a basic chat room content has been set up. If you want to use your business, or if you want to participate in some competitions, you can beautify the UI and optimize the details.

You can directly copy the code in the article, paste the use, according to the operation, there will be no problem. If you want source code files, follow my public account to reply to the chat room.