1.需要后端給你一個(gè)ws的接口比如:
ws://192.168.2.19:8080/chat/${name}
我這里的name是后端要求登錄成功后搞得
2.后端給我個(gè)登錄的接口,需要登錄后才能實(shí)現(xiàn)長鏈接
const login = (name) => {
toLogin(data).then(res => {
console.log(res);
init(name)
}).catch(err => {
console.log(err);
})
}
3.封裝init方法
const init = (name) => {
if(typeof(WebSocket) === "undefined"){
alert("您的瀏覽器不支持socket")
}else{
const ws = new WebSocket(`ws://192.168.2.19:8080/chat/${name}`)
// //連接發(fā)生錯(cuò)誤的回調(diào)方法
ws.onerror = function () {
console.log("ws連接發(fā)生錯(cuò)誤");
};
//連接成功建立的回調(diào)方法
ws.onopen = function () {
console.log("ws連接成功");
}
//接收到消息的回調(diào)方法
ws.onmessage = function (event) {
console.log(name + '的',event.data);
}
//連接關(guān)閉的回調(diào)方法
ws.onclose = function () {
console.log("ws連接關(guān)閉");
}
}
}
網(wǎng)上找了一堆沒用的方法,不建議看文章來源:http://www.zghlxwxcb.cn/news/detail-623210.html
所有代碼合集文章來源地址http://www.zghlxwxcb.cn/news/detail-623210.html
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import {toLogin} from '../http/index'
let word = ref('')
const data = {
username:'zhangsan',
password:'123'
}
const login = (name) => {
toLogin(data).then(res => {
console.log(res);
init(name)
}).catch(err => {
console.log(err);
})
}
const init = (name) => {
if(typeof(WebSocket) === "undefined"){
alert("您的瀏覽器不支持socket")
}else{
const ws = new WebSocket(`ws://192.168.2.19:8080/chat/${name}`)
// //連接發(fā)生錯(cuò)誤的回調(diào)方法
ws.onerror = function () {
console.log("ws連接發(fā)生錯(cuò)誤");
};
//連接成功建立的回調(diào)方法
ws.onopen = function () {
console.log("ws連接成功");
}
//接收到消息的回調(diào)方法
ws.onmessage = function (event) {
console.log(name + '的',event.data);
}
//連接關(guān)閉的回調(diào)方法
ws.onclose = function () {
console.log("ws連接關(guān)閉");
}
}
}
</script>
<template>
<h1>Web Socket</h1>
<div>聊天框 <textarea type="text" v-model="word" ></textarea></div>
<button @click="login('zhangsan')">張三登錄</button>
<button @click="login('李四')">李四登錄</button>
<button @click="send">發(fā)送</button>
</template>
<style scoped>
</style>
到了這里,關(guān)于vue3使用websocket(親測(cè)解決)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!