如何通过套接字发送鼠标坐标

时间:2015-07-06 21:45:34

标签: java sockets applet

这是我想要做的:

使用服务器端的applet在客户端绘制applet。

我的想法是只发送鼠标坐标(当按下并拖动鼠标时),客户端将使用这些坐标进行绘制。

但是我没有关于如何在拖动鼠标时发送坐标的想法。

按下鼠标时的代码:

Test()

拖动鼠标时的代码:

public boolean mouseDown(Event e, int x, int y) {
    lastx = x; lasty = y;                    // Remember where the click was
    return true;

我如何以实时时间发送这些坐标?

1 个答案:

答案 0 :(得分:0)

我不确定您是如何将数据发送到客户端的,所以我会尽力建议您最好的方式。

假设您以对象形式从服务器向客户端发送数据,我将给您伪代码。

让我们在你的服务器上说出一个mousedown事件被解雇了

public boolean mouseDown(Event e, int x, int y) {
    lastx = x; lasty = y;                    // Remember where the click was
    client.send(new ServerClickEvent(x, y)); //Assuming you are using objects to send details to the client
    return true;
}

现在,在客户端,当您收到此对象时,您可以为服务器设置lastX和lastY。

因此,只要您在客户端从服务器获取对象,就会触发received(Object object)方法。

你能做的是,

public void received(Object object){
  if(object instanceof ServerClickEvent)
       setServerLastXAndLastY(object); // where setServerLastXAndLastY method will set lastX and lastY locations of the Server on the client side.
}

现在,当服务器上有拖动事件时,您可以类似地执行

public boolean mouseDrag(Event e, int x, int y) {
    client.send(new ServerMouseDragEvent(x, y));
    g.drawLine(lastx, lasty, x, y);   // Draw from last position to here
    lastx = x; lasty = y;                    // And remember new last position
    return true;

}

现在在客户端你可以做到

 public void received(Object object){
      if(object instanceof ServerMouseDragEvent)
           drawDragLine(object); // where drawDragLine method will draw the lines by taking x and y values from object and will change the lastX and lastY locations of the Server on the client side.
    }
相关问题