Bootstrap

webSocket前后端交互pc端版

前端代码

<!--
 * @Author: 第一好帅@宝
 * @Date: 2023-08-29 16:12:26
 * @LastEditTime: 2023-08-29 16:54:50
 * @FilePath: \websocket\ceshi.html
-->
<!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>

    <div class="msg"></div>
    <input type="text">
    <button>发送</button>
    <button class="bu">关闭连接</button>
    <div class="box"></div>
    <script>
        let inp = document.querySelector('input')
        let but = document.querySelector('button')
        let bu = document.querySelector('.bu')
        let ws = new WebSocket('ws://localhost:8001')
        console.log(ws);
        //初始化连接
        ws.onopen = function () {
            document.querySelector('.msg').innerHTML = '<h1>连接成功!</h1>'
            console.log('连接成功触发函数');
            ws.send('第一次连接')
        }
        //服务器关闭
        ws.onclose = function (e) {
            document.querySelector('.msg').innerHTML = '<h1>服务器关闭!</h1>'
            console.log('服务器关闭');
        }
        //连接出错
        ws.onerror = function (e) {
            document.querySelector('.msg').innerHTML = '<h1>连接出错了!</h1>'
            console.log('连接出错了');
        }
        //服务器返回数据触发函数
        ws.onmessage = function (e) {
            console.log(e.data);
            document.querySelector('.box').innerHTML = e.data
        }
        //向后端发送消息
        but.addEventListener('click', function () {
            if (inp.value.trim() != '') {
                ws.send(inp.value)
            }
        })
        //断开连接
        bu.addEventListener('click', function () {
            ws.close()
        })
    </script>
</body>

</html>

后端代码,使用nodejs

npm i nodejs-websocket
/*
 * @Author: 第一好帅@宝
 * @Date: 2023-08-29 15:52:49
 * @LastEditTime: 2023-08-29 16:48:17
 * @FilePath: \node\node.js
 */
var ws = require('nodejs-websocket');
 
console.log("开始建立连接...");
 
var server = ws.createServer(function (conn) {
 
  conn.on("connect", function (code) {
    console.log("开启连接" + code);
  });
 
  conn.on("text", function (result) {
    console.log("收到的信息为:" + result); //由Webtest.html中传来data 
    let a=result
    if (result == 1) {
      a="飞哥" //发送"success"至Webtest.html
    } else if (result == 2) {
      a="帆姐" //发送"success"至Webtest.html
    } else if (result == 3) {
      a='东哥'
    }else if(result==4){
      a="阳哥"
    }
 
//向前端发送消息
    conn.sendText('服务器返回数据:'+a);
  });
 
  conn.on("close", function (code) {
    console.log("关闭连接")
  });
 
  conn.on("error", function (code) {
    console.log("异常关闭")
  });
}).listen(8001);
 
console.log("WebSocket连接建立完毕");

运行 node xx.js

;