• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

147
Vistas
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.

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda