前端使用websocket發(fā)送消息的示例代碼
序言
今天來學習一下前端如何使用websocket發(fā)送消息
1 基礎介紹
1.1 什么是WebSocket
WebSocket 是一種在單個 TCP 連接上進行全雙工通信的協(xié)議,它可以讓客戶端和服務器之間進行實時的雙向通信。與傳統(tǒng)的 HTTP 請求不同,WebSocket 使用了一個長連接,在客戶端和服務器之間保持持久的連接,從而可以實時地發(fā)送和接收數(shù)據(jù)。
在 WebSocket 中,客戶端和服務器之間可以互相發(fā)送消息。
客戶端可以使用 JavaScript 中的 WebSocket API 發(fā)送消息到服務器,也可以接收服務器發(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 對象,指定了服務器的地址。然后在
onopen回調(diào)函數(shù)中,發(fā)送了一個消息到服務器。當服務器發(fā)送消息到客戶端時,onmessage回調(diào)函數(shù)會被觸發(fā),從而可以處理服務器發(fā)送的消息。如果出現(xiàn)錯誤或者連接被關閉,onerror和onclose回調(diào)函數(shù)會被觸發(fā),從而可以處理這些事件。需要注意的是,在使用 WebSocket 發(fā)送消息之前,必須先建立 WebSocket 連接。在上面的代碼中,通過創(chuàng)建一個 WebSocket 對象來建立連接,然后在
onopen回調(diào)函數(shù)中發(fā)送消息到服務器。如果在連接建立之前就嘗試發(fā)送消息,那么這些消息將無法發(fā)送成功。
2 案例講解
2.1 vue怎么用websocket發(fā)送請求
在 Vue 中使用 WebSocket,可以借助
WebSocket對象來創(chuàng)建 WebSocket 連接,并通過send()方法向服務器發(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ā)送到服務器。
- 在 handleMessage 方法中,將從服務器接收到的消息添加到 messages 數(shù)組中,從而可以在界面上顯示出來。
- 在組件銷毀之前,需要調(diào)用 close() 方法關閉 WebSocket 連接。
需要注意的是,在使用 WebSocket 時,需要考慮跨域問題。如果 WebSocket 連接的 URL 和當前頁面的 URL 不同,那么需要在服務器端進行相應的跨域設置。同時,需要注意在發(fā)送和接收消息時的數(shù)據(jù)格式,通常需要將數(shù)據(jù)轉換為 JSON 字符串進行傳輸。
2.2 this.message 怎么組裝
在上面的 Vue 組件中,
this.message是用戶輸入的消息文本,可以通過綁定v-model實現(xiàn)雙向綁定。
當用戶輸入消息后,可以將消息文本直接發(fā)送到服務器。在發(fā)送消息之前,可以根據(jù)需要對消息進行組裝,例如添加消息的發(fā)送者、時間等信息,以便在服務器端進行更好的處理。
以下是一個示例,假設要發(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ā)送消息之前,將當前時間戳賦值給 timestamp 屬性,并將消息對象轉換為 JSON 字符串,然后通過 WebSocket 發(fā)送出去。
- 在接收到服務器發(fā)送的消息后,將 JSON 字符串解析為消息對象,并將消息對象添加到 messages 數(shù)組中,從而可以在界面上顯示出來。
2.3 發(fā)送示例
要發(fā)送這個:
{
"msg_id": "1",
"msg_type": "test",
"content": {
"count": "10"
}
}代碼實現(xiàn)
要發(fā)送這個 JSON 數(shù)據(jù),可以先將其轉換為字符串,然后通過 WebSocket 發(fā)送出去。
以下是一個示例代碼,假設使用
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ù)中處理服務器返回的響應數(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 請求,并在請求成功或失敗時打印相應的日志。
2.4 接收示例
返回參數(shù)是這個,我該怎么接收:
{
"msg_id": "1",
"msg_type": "test",
"code": 0,
"err_msg": "Success.",
"content": {
"count": "20"
}
}代碼實現(xiàn)
要接收和處理服務器返回的 JSON 數(shù)據(jù),可以在
onmessage回調(diào)函數(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()方法將接收到的消息轉換為 JSON 對象,并在onmessage回調(diào)函數(shù)中處理返回的數(shù)據(jù)。如果返回的數(shù)據(jù)中code屬性為 0,表示請求成功,可以在控制臺打印返回的數(shù)據(jù);否則,表示請求失敗,可以在控制臺打印錯誤信息。
到此這篇關于前端如何使用websocket發(fā)送消息的文章就介紹到這了,更多相關websocket發(fā)送消息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
學習Bootstrap滾動監(jiān)聽 附調(diào)用方法
這篇文章主要為大家全面解析Bootstrap中滾動監(jiān)聽的使用方法,感興趣的小伙伴們可以參考一下2016-07-07

