WebSocket usage examples

The example effect is as follows:

 

To use node to create a server program, first install the node environment.

Then install the WebSocket dependency package. The command to install the WebSocket dependency package is:

npm i ws -S

 After the package is installed, create app.js as a back-end service project file. The code is as follows:


//引入ws包
const WebSocket = require('ws');

//创建WebSoctet.Server对象
const wss = new WebSocket.Server({
    port: 1111
});

//对客户端连接事件进行监听
//client 客户端的连接soctet对象
wss.on('connection', client => {
    console.log("有客户端连接成功");
    //对客户端的message事件进行监听
    //msg 客户端发送给服务端的数据
    client.on('message', msg => {
        console.log("客户端发送数据给服务端了,数据是:" + msg);
        //由服务端向前端发送数据
        client.send("前端你好,我是从后端发送过来的数据.");
    });
});

 

Create an html file, as the front-end call page, the code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket实例</title>
</head>

<body>
    <button id="connect">连接服务端</button>
    <button id="send" disabled="true">发送数据</button>
    <br> 从服务端接收的数据如下: <br>
    <span style="color:red" id="result"></span>

    <script>
        var connect = document.querySelector('#connect');
        var send = document.querySelector('#send');
        var result = document.querySelector('#result');

        let ws = null;
        connect.onclick = function() {
            ws = new WebSocket('ws://localhost:1111');
            ws.onopen = () => {
                console.log('连接服务器成功了');
                send.disabled = false;
            }
            ws.onclose = () => {
                console.log('连接服务器失败了');
                send.disabled = true;
            }
            ws.onmessage = (msg) => {
                console.log('接收到服务器发送过来的数据');
                result.innerHTML = msg.data;
            }
        }

        send.onclick = function() {
            ws.send('后端你好,我是从前端发送过来的数据');
        }
    </script>
</body>

</html>

After the front-end and back-end codes are created, start the back-end program first. The command line is:

node app.js

 After the program starts, open the html page in the browser to test the program.

 

Specific steps are as follows:

 

You can see that the server and the client have successfully established a connection and can send data in both directions.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/111088532