Recommand · June 14, 2021 0

Socket.on/socket.emit doesn't invoke

I am making a collaborative whiteboard app. I use the socket-io library. Now I have a server which works fine and in my App.js the following function:

socket.on("canvas-data", function(data){
      var interval = setInterval(function(){
        //if(isDrawing) return;
        //setIsDrawing(true);
        clearInterval(interval);
        //var stageData = JSON.parse(data);
          alert(data)
        //var layer = new Konva.Layer();
        //var lines = new Konva.Image(
        //{
         // stroke: stageData.attrs.stroke,
        //  strokeWidth: stageData.attrs.strokeWidth,
        //  points: stageData.attrs.points
        //x: stageData.x,
        //y: stageData.y,
        //src: stageData.src
        //})
      //layer.add(lines);
  
      //stageEl.current.add(layer);
  
      })
    }, 200)

Right now most of it is commented out for testing purposes. Now I tried this this with the konva lines.

   stage.on("mouseup touchend", function() {
  isDrawing = false;
  socket.emit("canvas-data", lastLine);
});

This worked perfectly, as expected. But now I also want to make this work with my konva images. So I did the following:

<div
        onDrop={(e) => {
          e.preventDefault();
          // register event position
          stageEl.current.setPointersPositions(e);
          // add image
          setImages(
            images.concat([
              {
                ...stageEl.current.getPointerPosition(),
                src: dragUrl.current,
              },
            ])
          );
          socket.emit("canvas-data", [{
            ...stageEl.current.getPointerPosition(),
            src: dragUrl.current,
          }]);     
        }}
        onDragOver={(e) => {
          e.preventDefault();
          console.log(e.x)
        }
        }
      >

Basically what it’s doing is that whenever an image in dropped onto the canvas, the socket.emit(...) should invoke. But it doesn’t happen and I don’t know why. In the first code piece you can see I use alert() to test whether my socket.on() function works with the images, but whenever I drop the image onto the canvas, there’s no alert. I have no idea why it doesn’t work, since it does work perfectly with the konva lines.

This is btw the io.on() function in my server:

io.on('connection', (socket)=> {
      connections.push(socket);
      console.log(`${socket.id} has connected`);

      socket.on("disconnect", (reason) => {
            console.log(`${socket.id} is disconnected`);
            connections = connections.filter((con) => con.id !== socket.id);
      });
      socket.on('canvas-data', (data)=> {
            console.log(data);
            socket.broadcast.emit('canvas-data', data);
            
      });
})

Does anyone know why it doesn’t work?