1. 程式人生 > 實用技巧 >websocket,vue連結

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>