Search code examples
javasocketsmouseeventmouselistener

Java, sending MouseEvents over socket, how can I do it?


I've tried implementing MouseListener and sending it over ObjectInputStream, but I don't have a sense of direction on how to make the server receive such actions, recognize what button is pressed, and act on it.

How can I send mouse events such as mousePressed from a client to a server, so that the server can perform the mouse events?

Client - Records mouse actions, Server - Receives and Performs such actions.


Solution

  • You can only send serializable concepts over the wire and a mouselistener is unlikely to be.

    You have code. You wish for this code to respond to the event.

    For that to happen, the code and the information about the event (that it has occurred, i.e. that the user clicked, and the details about this event, i.e. where they clicked, which button they used, etc) have to be in the same place.

    Bring the event to the code. Don't bring the code to the event. You serialize the MouseEvent, not the listener.

    Have MouseListener running on the client. This listener sends the relevant information about the event to the server. I wouldn't use ObjectXStream at all, but write an actual API of sorts, using e.g. JSON or protobuf or some other real protocol to talk to the server, preferably in HTTPS, as that tunnels and tests easier.