zoukankan      html  css  js  c++  java
  • websocket,vue链接

    router.js

    var express = require('express');
    var expressWs = require('express-ws');
    
    var router = express.Router();
    expressWs(router);
    
    router
      .ws('/user', function (ws, req){
        //   ws.on('message', function (msg) {
        //       // 业务代码
        //       console.log(123)
        //   })
        ws.send("连接成功")
        let interval
        // 连接成功后使用定时器定时向客户端发送数据,同时要注意定时器执行的时机,要在连接开启状态下才可以发送数据
        interval = setInterval(() => {
          if (ws.readyState === ws.OPEN) {
            ws.send(Math.random().toFixed(2))
          } else {
            clearInterval(interval)
          }
        }, 1000)
        // 监听客户端发来的数据,直接将信息原封不动返回回去
        ws.on("message", msg => {
          ws.send(msg)
        })
       })
      .get('/user', function(req, resp) {
      })
      .post('/user', function(req, resp) {
      })
    
    module.exports = router;
    

      index.js

    var express = require('express');
    var expressWs = require('express-ws');
    var router = require('./router');
    
    var app = express();
    expressWs(app);
    app.use('/ifc', router);
    
    app.listen(3000);
    

      node index.js 启动

    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="websocket">
            <div class="receive">
                <p>服务端返回的消息</p>
                <div id="receive-box"></div>
            </div>
            <div class="send">
                <textarea type="text" id="msg-need-send"></textarea>
                <p>
                    <button id="send-btn">点击发消息给服务端</button>
                </p>
            </div>
            <button id="exit">关闭连接</button>
        </div>
    </body>
    <script>
        const msgBox = document.getElementById("msg-need-send")
        const sendBtn = document.getElementById("send-btn")
        const exit = document.getElementById("exit")
        const receiveBox = document.getElementById("receive-box")
    
        // 创建一个webSocket对象
        const ws = new WebSocket("ws://localhost:3000/ifc/user")
        ws.onopen = e => {
            // 连接后监听
            console.log(`WebSocket 连接状态: ${ws.readyState}`)
        }
    
        ws.onmessage = data => {
            // 当服务端返回数据的时候,放到页面里
            receiveBox.innerHTML += `<p>${data.data}</p>`
            receiveBox.scrollTo({
                top: receiveBox.scrollHeight,
                behavior: "smooth"
            })
        }
    
        ws.onclose = data => {
            // 监听连接关闭
            console.log("WebSocket连接已关闭")
            console.log(data);
        }
    
        sendBtn.onclick = () => {
            // 点击发送按钮。将数据发送给服务端
            ws.send('消息')
        }
        exit.onclick = () => {
            // 客户端主动关闭连接
            ws.close()
        }
        var a = 0
        setInterval(() => {
            a++
            ws.send('消息' + a)
        }, 1000)
    </script>
    
    </html>

      vue 方式

    <template>
        <div>
            <button @click="send">发消息</button>
        </div>
    </template>
    
    <script>
    export default {
        data () {
            return {
                path:"ws://localhost:3000/ifc/user",
                socket:""
            }
        },
        mounted () {
            // 初始化
            this.init()
        },
        methods: {
            init: function () {
                if(typeof(WebSocket) === "undefined"){
                    alert("您的浏览器不支持socket")
                }else{
                    // 实例化socket
                    this.socket = new WebSocket(this.path)
                    // 监听socket连接
                    this.socket.onopen = this.open
                    // 监听socket错误信息
                    this.socket.onerror = this.error
                    // 监听socket消息
                    this.socket.onmessage = this.getMessage
                }
            },
            open: function () {
                console.log("socket连接成功")
            },
            error: function () {
                console.log("连接错误")
            },
            getMessage: function (msg) {
                console.log(msg.data)
            },
            send: function () {
                this.socket.send('2222')
            },
            close: function () {
                console.log("socket已经关闭")
            }
        },
        destroyed () {
            // 销毁监听
            this.socket.onclose = this.close
        }
    }
    </script>
    
    <style>
    
    </style>
    

      

  • 相关阅读:
    Tomcat 服务器体系结构
    tomcat的下载和启动
    tomcat解决端口号占用问题
    我的wmware
    Xshell的使用
    GCC的-wl,-rpath=参数
    Matlab图像处理(01)-Matlab基础
    CMake最好的学习资料
    使用valgrind进行内存泄漏和非法内存操作检测
    CLion提示can't find stdio.h等错误
  • 原文地址:https://www.cnblogs.com/qq364735538/p/14043274.html
Copyright © 2011-2022 走看看