最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

前端使用websocket發(fā)送消息的示例代碼

 更新時間:2023年07月21日 16:23:31   作者:顏淡慕瀟  
WebSocket是一種在單個TCP連接上進行全雙工通信的協(xié)議,它可以讓客戶端和服務(wù)器之間進行實時的雙向通信,這篇文章主要介紹了前端使用websocket發(fā)送消息的示例代碼,需要的朋友可以參考下

序言

今天來學(xué)習(xí)一下前端如何使用websocket發(fā)送消息

1 基礎(chǔ)介紹

1.1 什么是WebSocket

WebSocket 是一種在單個 TCP 連接上進行全雙工通信的協(xié)議,它可以讓客戶端和服務(wù)器之間進行實時的雙向通信。與傳統(tǒng)的 HTTP 請求不同,WebSocket 使用了一個長連接,在客戶端和服務(wù)器之間保持持久的連接,從而可以實時地發(fā)送和接收數(shù)據(jù)。

在 WebSocket 中,客戶端和服務(wù)器之間可以互相發(fā)送消息。

客戶端可以使用 JavaScript 中的 WebSocket API 發(fā)送消息到服務(wù)器,也可以接收服務(wù)器發(fā)送的消息。

1.2 代碼示例

下面是一個使用 WebSocket API 發(fā)送消息的代碼示例:

var socket = new WebSocket("ws://example.com/socketserver");
socket.onopen = function(event) {
  socket.send("Hello server!");
};
socket.onmessage = function(event) {
  console.log("Received message from server: " + event.data);
};
socket.onerror = function(event) {
  console.log("WebSocket error: " + event.error);
};
socket.onclose = function(event) {
  console.log("WebSocket connection closed with code " + event.code);
};

在上面的代碼中,首先創(chuàng)建了一個 WebSocket 對象,指定了服務(wù)器的地址。然后在 onopen 回調(diào)函數(shù)中,發(fā)送了一個消息到服務(wù)器。當(dāng)服務(wù)器發(fā)送消息到客戶端時,onmessage 回調(diào)函數(shù)會被觸發(fā),從而可以處理服務(wù)器發(fā)送的消息。如果出現(xiàn)錯誤或者連接被關(guān)閉,onerror 和 onclose 回調(diào)函數(shù)會被觸發(fā),從而可以處理這些事件。

需要注意的是,在使用 WebSocket 發(fā)送消息之前,必須先建立 WebSocket 連接。在上面的代碼中,通過創(chuàng)建一個 WebSocket 對象來建立連接,然后在 onopen 回調(diào)函數(shù)中發(fā)送消息到服務(wù)器。如果在連接建立之前就嘗試發(fā)送消息,那么這些消息將無法發(fā)送成功。

2 案例講解

2.1 vue怎么用websocket發(fā)送請求

在 Vue 中使用 WebSocket,可以借助 WebSocket 對象來創(chuàng)建 WebSocket 連接,并通過 send() 方法向服務(wù)器發(fā)送消息。

下面是一個基本的 Vue 組件,演示如何使用 WebSocket 發(fā)送和接收消息:

<template>
  <div>
    <input v-model="message" @keyup.enter="sendMessage">
    <button @click="sendMessage">Send</button>
    <ul>
      <li v-for="msg in messages">{{ msg }}</li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: '',
      messages: [],
      socket: null
    }
  },
  created() {
    this.socket = new WebSocket('ws://localhost:3000')
    this.socket.addEventListener('message', this.handleMessage)
  },
  beforeDestroy() {
    this.socket.close()
  },
  methods: {
    sendMessage() {
      this.socket.send(this.message)
      this.message = ''
    },
    handleMessage(event) {
      this.messages.push(event.data)
    }
  }
}
</script>

在上面的代碼中,

  • 首先在 created 鉤子函數(shù)中創(chuàng)建了一個 WebSocket 對象,并添加了一個消息處理函數(shù) handleMessage。
  • 在 sendMessage 方法中,將用戶輸入的消息發(fā)送到服務(wù)器。
  • 在 handleMessage 方法中,將從服務(wù)器接收到的消息添加到 messages 數(shù)組中,從而可以在界面上顯示出來。
  • 在組件銷毀之前,需要調(diào)用 close() 方法關(guān)閉 WebSocket 連接。

需要注意的是,在使用 WebSocket 時,需要考慮跨域問題。如果 WebSocket 連接的 URL 和當(dāng)前頁面的 URL 不同,那么需要在服務(wù)器端進行相應(yīng)的跨域設(shè)置。同時,需要注意在發(fā)送和接收消息時的數(shù)據(jù)格式,通常需要將數(shù)據(jù)轉(zhuǎn)換為 JSON 字符串進行傳輸。

2.2 this.message 怎么組裝

在上面的 Vue 組件中,this.message 是用戶輸入的消息文本,可以通過綁定 v-model 實現(xiàn)雙向綁定。

當(dāng)用戶輸入消息后,可以將消息文本直接發(fā)送到服務(wù)器。在發(fā)送消息之前,可以根據(jù)需要對消息進行組裝,例如添加消息的發(fā)送者、時間等信息,以便在服務(wù)器端進行更好的處理。

以下是一個示例,假設(shè)要發(fā)送的消息格式為一個包含文本和時間戳的 JSON 對象:

<template>
  <div>
    <input v-model="message.text" @keyup.enter="sendMessage">
    <button @click="sendMessage">Send</button>
    <ul>
      <li v-for="msg in messages">{{ msg.text }} ({{ msg.timestamp }})</li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: {
        text: '',
        timestamp: null
      },
      messages: [],
      socket: null
    }
  },
  created() {
    this.socket = new WebSocket('ws://localhost:3000')
    this.socket.addEventListener('message', this.handleMessage)
  },
  beforeDestroy() {
    this.socket.close()
  },
  methods: {
    sendMessage() {
      this.message.timestamp = new Date().toISOString()
      const json = JSON.stringify(this.message)
      this.socket.send(json)
      this.message.text = ''
      this.message.timestamp = null
    },
    handleMessage(event) {
      const msg = JSON.parse(event.data)
      this.messages.push(msg)
    }
  }
}
</script>

在上面的代碼中,

  • this.message 是一個包含 text 和 timestamp 兩個屬性的對象,在用戶輸入消息后,將消息文本賦值給 text 屬性。
  • 在發(fā)送消息之前,將當(dāng)前時間戳賦值給 timestamp 屬性,并將消息對象轉(zhuǎn)換為 JSON 字符串,然后通過 WebSocket 發(fā)送出去。
  • 在接收到服務(wù)器發(fā)送的消息后,將 JSON 字符串解析為消息對象,并將消息對象添加到 messages 數(shù)組中,從而可以在界面上顯示出來。

2.3 發(fā)送示例

要發(fā)送這個:

{
"msg_id": "1",
"msg_type": "test",
"content": {
"count": "10"
}
}

代碼實現(xiàn)

要發(fā)送這個 JSON 數(shù)據(jù),可以先將其轉(zhuǎn)換為字符串,然后通過 WebSocket 發(fā)送出去。

以下是一個示例代碼,假設(shè)使用 axios 庫來發(fā)送 WebSocket 請求:

import axios from 'axios'
const ws = new WebSocket('ws://localhost:3000')
ws.onopen = () => {
  const data = {
    msg_id: '1',
    msg_type: 'test',
    content: {
      count: '10'
    }
  }
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}
ws.onmessage = (event) => {
  const response = JSON.parse(event.data)
  console.log('Received message:', response)
}
ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}
function sendWebSocketRequest(data) {
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}
export default {
  sendWebSocketRequest
}

在上面的代碼中,

  • 首先創(chuàng)建了一個 WebSocket 對象,并在 onopen 回調(diào)函數(shù)中發(fā)送了一條 WebSocket 請求。
  • 在 onmessage 回調(diào)函數(shù)中處理服務(wù)器返回的響應(yīng)數(shù)據(jù)。
  • 在 onerror 回調(diào)函數(shù)中處理 WebSocket 錯誤。

優(yōu)化

為了方便使用,將發(fā)送 WebSocket 請求的代碼封裝在 sendWebSocketRequest 函數(shù)中,可以在其他組件中直接調(diào)用該函數(shù)來發(fā)送 WebSocket 請求。例如:

import { sendWebSocketRequest } from '@/api/websocket'
sendWebSocketRequest({
  msg_id: '1',
  msg_type: 'test',
  content: {
    count: '10'
  }
}).then(response => {
  console.log('Received response:', response)
}).catch(error => {
  console.error('WebSocket error:', error)
})

在上面的代碼中,調(diào)用 sendWebSocketRequest 函數(shù)發(fā)送 WebSocket 請求,并在請求成功或失敗時打印相應(yīng)的日志。

2.4 接收示例

返回參數(shù)是這個,我該怎么接收:

{
"msg_id": "1",
"msg_type": "test",
"code": 0,
"err_msg": "Success.",
"content": {
"count": "20"
}
}

代碼實現(xiàn)

要接收和處理服務(wù)器返回的 JSON 數(shù)據(jù),可以在 onmessage 回調(diào)函數(shù)中處理接收到的消息。

以下是一個示例代碼,假設(shè)使用 axios 庫發(fā)送 WebSocket 請求:

import axios from 'axios'
const ws = new WebSocket('ws://localhost:3000')
ws.onopen = () => {
  const data = {
    msg_id: '1',
    msg_type: 'test',
    code: 0,
    err_msg: 'Success.',
    content: {
      count: '20'
    }
  }
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}
ws.onmessage = (event) => {
  const response = JSON.parse(event.data)
  console.log('Received message:', response)
  // 處理返回的數(shù)據(jù)
  if (response.code === 0) {
    console.log('Success:', response.content)
  } else {
    console.error('Error:', response.err_msg)
  }
}
ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}
function sendWebSocketRequest(data) {
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}
export default {
  sendWebSocketRequest
}

在上面的代碼中,使用 JSON.parse() 方法將接收到的消息轉(zhuǎn)換為 JSON 對象,并在 onmessage 回調(diào)函數(shù)中處理返回的數(shù)據(jù)。如果返回的數(shù)據(jù)中 code 屬性為 0,表示請求成功,可以在控制臺打印返回的數(shù)據(jù);否則,表示請求失敗,可以在控制臺打印錯誤信息。

到此這篇關(guān)于前端如何使用websocket發(fā)送消息的文章就介紹到這了,更多相關(guān)websocket發(fā)送消息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

西和县| 湖北省| 鄯善县| 贵港市| 石屏县| 南城县| 温泉县| 安福县| 玉林市| 黄大仙区| 高雄县| 台州市| 偏关县| 尖扎县| 麻阳| 敖汉旗| 石柱| 昭苏县| 密云县| 齐齐哈尔市| 铜山县| 济宁市| 西林县| 永和县| 瑞安市| 安顺市| 阿坝| 巨野县| 彭山县| 鄂托克前旗| 渝中区| 红原县| 喀喇沁旗| 大庆市| 漳浦县| 通城县| 乐东| 康保县| 吴忠市| 鹤峰县| 二连浩特市|