[英]socket.io getting error message while using broadcast
實際上我正在嘗試使用 vueJS 和 socket.io 創建聊天應用程序,所以這是我到目前為止所做的
<script>
import {io} from "socket.io-client";
export default {
data() {
return {
socketInstance: io("http://localhost:3001"),
};
},
methods: {
async handleSendMessage(message) {
const postParams = {
ip: this.userData.ip,
message: message,
user_type: "customer",
};
const {data} = await axios.post(
"http://localhost:3001/api/message",
postParams
);
this.messages.push(data.message);
this.socketInstance.broadcast.emit("new_message", {
message: data.message,
socket_id: this.socketInstance.id,
});
//HERE AM GETTING ERROR WHILE USING BROADCAST
}
},
mounted() {
this.socketInstance.on("new_message", ({message, socket_id}) => {
if (message.ip == this.userData.ip) {
this.messages.push(message);
}
});
},
};
</script>
基本上, handleSendMessage函數負責發送消息並發出事件,但是當我這樣做時
this.socketInstance.emit("new_message", {
message: data.message,
socket_id: this.socketInstance.id,
});
那么它工作正常,但你知道我會收到重復的消息,所以我用
this.socketInstance.broadcast.emit("new_message", {
message: data.message,
socket_id: this.socketInstance.id,
});
並得到以下錯誤
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'emit')
我不知道為什么會收到此錯誤。 對不起,我的英語不好。
在 socket.io 文檔中是這樣寫的:
請注意,廣播是僅服務器功能。
.broadcast
僅用於服務器端。 您向所有連接的客戶端廣播某些內容,而不是 client-to-client 。
相關文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.