欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue+Nodejs使用WebSocket創(chuàng)建一個(gè)簡(jiǎn)易聊天室教程

 更新時(shí)間:2025年06月16日 09:13:02   作者:不想起名55  
這篇文章主要介紹了Vue+Nodejs使用WebSocket創(chuàng)建一個(gè)簡(jiǎn)易聊天室教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、頁(yè)面效果

二、架構(gòu)流程

使用vue編寫前端頁(yè)面,nodejs處理服務(wù)端消息,WebSocket進(jìn)行實(shí)時(shí)通信

三、技術(shù)細(xì)節(jié)

1.客戶端

<template>
    <div>
        <form onsubmit="return false">
            <textarea  id="responseTest"  style="width: 500px; height: 300px"  ></textarea>
            <br />
            <input  type="text"  name="message"  style="width: 300px"  :value="inputVal"  @input="input"  />
            <input type="button" value="發(fā)送消息" @click="send(inputVal)" />
            <input type="button" value="清空聊天記錄" @click="clean" />
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
          inputVal: '歡迎來(lái)到二二得四的聊天室',
          socket:null
        }
    },
    methods: {
        testWebsocket() {
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket
            }
            if (window.WebSocket) {
                this.socket = new WebSocket('ws://localhost:8088/ws')
              this.socket.onmessage = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = ta.value + '\n' + event.data
                }
              this.socket.onopen = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = '連接開啟!'
                }
                this.socket.onclose = function (event) {
                    var ta = document.getElementById('responseTest')
                    ta.value = '連接關(guān)閉!'
                }
            } else {
                alert('你的瀏覽器不支持WebSocket')
            }
        },
        input(e) {
            this.inputVal = e.detail.value
        },
        clean() {
            document.getElementById('responseTest').value = ''
        },
        send(message) {
            if (!window.WebSocket) {
                return
            }
          if (this.socket.readyState === WebSocket.OPEN) {
              this.socket.send(message)
            } else {
                alert('連接沒有開啟')
            }
        },
    },
    mounted() {
        this.testWebsocket()
    },
}
</script>

<style></style>

2. 服務(wù)端

使用的是nodejs

const ws = require('ws')

const webserve = new ws.Server({port:8088})

//打開WebSocket服務(wù)器:通過(guò)監(jiān)聽open事件打開服務(wù)器
webserve.on('open',function open() {
    console.log('connected')
})

//關(guān)閉WebSocket服務(wù)器:通過(guò)監(jiān)聽close事件關(guān)閉服務(wù)器
webserve.on('close',function close() {
    console.log('disconnected')
})

//監(jiān)聽連接:ws通過(guò)connection事件來(lái)監(jiān)聽連接
webserve.on('connection',function connection(res,req) {
    const ip1 =  req.headers['x-forwarded-for'] || req.socket.remoteAddress
    const port1 = req.socket.remotePort
    const clientName = ip1+port1
    console.log('連接已開啟,開始發(fā)送消息')

    // 發(fā)送數(shù)據(jù):ws通過(guò)send()方法來(lái)發(fā)送到客戶端數(shù)據(jù)
    // res.send('welcome,'+clientName)

  //接收數(shù)據(jù):ws通過(guò)message事件來(lái)接收數(shù)據(jù)。當(dāng)客戶端有消息發(fā)送給服務(wù)器時(shí),服務(wù)器就能夠觸發(fā)該消息
    res.on('message',function incoming(message) {
        console.log('received: %s from %s',message,clientName)

        /**
         * 準(zhǔn)備的狀態(tài):ws中WebSocket類具有以下4中準(zhǔn)備狀態(tài)
         * 1、CONNCETION:值為0,表示連接還沒有打開
         * 2、OPEN:值為1,表示連接已經(jīng)打開,可以通信了
         * 3、CLOSING:值為2,表示連接正在關(guān)閉
         * 4、CLOSED:值為2,表示連接已經(jīng)關(guān)閉
         */
        webserve.clients.forEach(function each(client) {
            if(client.readyState === ws.OPEN){
                client.send(message.toString())
            }
        })
    })
})

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論