Native JavaScript+WebSocket+nodejs realizes chat room function

Codewords are not easy, and helpful students hope to pay attention to my WeChat official account: Code Program Life, thanks! The code is for your own use.

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

Now various websites, apps, and small programs are accompanied by instant messaging functions. The main application of WebSocket is instant messaging .

The introduction of WebSocket on the Internet is very, very detailed, and I will not introduce too much.

The emergence of WebSocket solved the "ugliness" of http polling in ancient times.

My video uses native JavaScript+nodejs to implement a basic chat room function.

I first introduce a catalog file:
Insert picture description here

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

Front end part:

entry.html content:

<!DOCTYPE html>
<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="请输入用户名"/>
    <button id="enter">进入聊天室</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('用户名不能小于6位');
                    return;
                }
                storage.setItem('username',username);
                location.href = 'index.html';
            }
            init();
        })(document,localStorage,location);
    </script>
</body>
</html>

This page is mainly for a login, it is a bit rough, no UI is written, mainly for storing 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-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul id="list">
        <input type="text" id="message" placeholder="请输入消息" />
        <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}</p>
            `
            return oItem;
        }
    </script>
</body>
</html>

This page is the content of the chat room . It is accompanied by a lot of dom operations. It may be a bit messy. I have no sub-modules. It is all written together for easy copy and paste.

The front-end part actually instantiates a WebSocket object. Whether it is a front-end or a back-end, WebSocket exists in an event-driven way.

The main front-end events are open, close, error, and message .

The functions of open, close, and error are the same as the names, so there is no need to explain too much.

Mainly the message event, which mainly receives information pushed from the backend .

Backend

The back-end must install the ws module before writing , and open the console for input

npm i ws -s

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);

The backend uses nodejs , which is also executed in an event-driven manner.

The main events are: open, close, error, message, and connection. The
first three events are still as they are.

The message event is stored in the parameter of the connection event , so the message event must be bound in the connection .

connection is an event representing whether the communication is successfully connected.

The parameter of message is the information passed from the front end .
Then what is to be done is to distribute the received front-end information to all people in the chat room.

At the very top of the code , we instantiated a Server object of the ws module . There is a clients attribute in the
Server object , and all people who log in to the chat room are mounted on this clients attribute. So we only need the forEach loop to distribute the received front-end information to everyone .

In fact, until now we have completed a minimum of based WebSocket technology of native JavaScript implementation chat rooms .

I opened a chrome browser and uc browser respectively.
Let's look at the effect:
Insert picture description here

No problem, the content of a most basic chat room has been set up.
If you want to be commercial or participate in some competitions, you can beautify the UI and optimize some detailed operations.

You can directly copy the code in the article, paste it, and follow the operation without any problems .
If you want source code files , just follow my official account and reply to the chat room .


There is a WeChat mini program course design, complete design needs, contact personal QQ: 505417246

Pay attention to the following WeChat public account, you can receive WeChat applet, Vue, TypeScript, front-end, uni-app, full stack, Nodejs, Python and other practical learning materials. The
latest and most complete front-end knowledge summary and project source code will be released to the WeChat public as soon as possible No., please pay attention, thank you!

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46171043/article/details/113126405