0

hola estoy intentando hacer un web-socket para usar con p5js.org, pero la única cosa que me funciona es esto:https://socketservice.herokuapp.com/ la sintaxis es la siguiente:

SocketService.init( 'my-awesome-room', socket => {
    socket.on( 'my-event', data => console.log( data ) )

    htmlbutton.addEventListener("click",socket.emit( 'my-event', { msg: "hello from button" } ))

    socket.on( 'room-joined', room => {
        console.log( `socket joined ${ room }` )

        socket.emit( 'my-event', { msg: `hello from ${ window.location }` } )
    } )
} )

y me gustaría usar algo mas simple:

function Socket(room,callback){
  this.room=room;
  this.recived=callback;
  this.send=function(obj){

  }
}

juntando los dos códigos... cuando recibo un mensaje llamo al callback y ningún problema, la cosa es cuando quiero enviar un mensaje desde cualquier parte de mi código debería llamar Socket.send(object) y esto disparar un evento dentro del socketservice como el del botón y ejecutar el socket.emit:?

button.addEventListener("click",callback)

entonces como disparo un evento virtual?

o se os ocurre algo mejor?

gracias:)

3
  • Hello, we are at Stackoverflow in Spanish please edit your question by translating it so it can be accepted and answered ;)
    – Israel-ICM
    el 11 dic. 2019 a las 19:26
  • gracias, ya lo he traducido el 11 dic. 2019 a las 19:37
  • intenta con button.click() el 11 dic. 2019 a las 20:01

1 respuesta 1

0

No se si he entendido bien tu problema. Esta es mi propuesta para manejar fácilmente eventos por socket en toda la app sin tener que reinstanciar todo de nuevo.

addEventListener("load", async () => {

    await SocketManager.init('test-room');
    const htmlButton = document.getElementById('test');
    htmlButton.addEventListener("click", () => SocketManager.send('test message'))

});


class SocketManager {
    static socket;
    static debug = true;
    static room;
    static async init(room) {

        SocketManager.room = room;
        return new Promise((resolve) => {
            if (SocketManager.socket) {
                return resolve();
            }
            SocketService.init(room, socket => {
                SocketManager.socket = socket;
                if (SocketManager.debug) {
                    socket.on('room-joined', room => console.log(`socket connected ${room}`));
                }
                return resolve();
            });

        });
    }

    static send(msg, key = `${SocketManager.room}_defaultEvent`) {
        if (!SocketManager.socket) {
            throw new Error('Socket is not connected. Please use init function before send.');
        }
        SocketManager.socket.emit(key, msg)
    }
}

Y la parte de la vista para hacer pruebas solo tengo esto.

<body>
    <button id="test">test </button>

    <script src="https://socketservice.herokuapp.com/SocketService.min.js"></script>
    <script src="app.js"></script>
</body>

Básicamente el funcionamiento es el siguiente. Necesitas utilizar al menos una vez en la app el método init para conectarte a la room deseada. Después de esto puedes usar tantos send como necesites.

Te recomiendo separar la clase SocketManager en otro fichero para tener distribuido mejor el código.

Espero que te sirva.

Salu2.

1
  • muchas gracias, es justo lo que queria el 14 dic. 2019 a las 15:03

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.