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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM