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