Nodejs starts the websocket service locally, and the front end calls the local websocket interface for debugging

I used to use nodejs to start the local service debugging interface of http. Today, because I need to debug websocket, I use nodejs to start the local service. I will share a method of using nodejs to start the websocket service locally!
Starting the local websocket service requires nodejs-websocket, so let's initialize a node project first!
1. Open the terminal, first create a js file, and then use npm init -y to initialize the package management. You will get a folder like this.
insert image description here
2. Install nodejs-websocket: npm install nodejs-websocket
3. Write code in index.js

// 引入nodejs-websocket
const ws = require('nodejs-websocket');
// 定义监听的host地址跟port端口
const host = '127.0.0.1',
    port = 8000;
// 创建ws服务
const service = ws.createServer((conn) => {
    
    
    // 定义测试数据
    const data = ['消息1', '消息2', '消息3'];
    conn.on('text', (message) => {
    
    
        // 当收到消息的时候就开始定时推送
        console.log('message', message);
        setInterval(() => {
    
    
            // 随机推送message里的内容
            conn.sendText(data[(Math.random() * 2).toFixed(0)]);
        }, 5 * 1000);
    });
}).listen(port, host, () => {
    
    
    console.log('service---connection---');
});

4. Write an html page to test whether it is successful

<script>
    window.onload = () => {
      
      
        if ('WebSocket' in window) {
      
      
            // 创建websocket连接
            let ws = new WebSocket('ws://127.0.0.1:8000');
            // 成功连接的时候推送一条消息,此时服务端就可以开始推送数据了
            ws.onopen = () => {
      
      
                console.log('websocket链接成功---');
                ws.send('success');
            }
            ws.onmessage = (message) => {
      
      
                let data = message.data;
                console.log('获取websocket消息-', data);
            }
            ws.onerror = () => {
      
      
                console.error('websocket链接失败');
            }
        } else {
      
      
            console.error('当前设备不支持websocket');
        };
    };
</script>

5. Enter node index.js in the terminal to start our service, and then open the index.html page to see that the connection is successful and start receiving messages.
insert image description here

Guess you like

Origin blog.csdn.net/m0_46496355/article/details/128027844