简体   繁体   中英

socket.io getting error message while using broadcast

actually am trying to create chat app using vueJS and socket.io so here is what i have done so far

<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>

Basically handleSendMessage function is responsible for sending message and emit an event but when I do

this.socketInstance.emit("new_message", {
  message: data.message,
  socket_id: this.socketInstance.id,
 });

then it's works fine but as you know i will get duplicate messages so i used

this.socketInstance.broadcast.emit("new_message", {
  message: data.message,
  socket_id: this.socketInstance.id,
 });

and got following error

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'emit')

I don't know why am getting this error. Sorry for my bad English.

It is written in the socket.io documentation as follows:

Please note that broadcasting is a server-only feature.

.broadcast is only used on the server-side. You broadcast something to all connected clients, not client-to-client .

Related documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM