在 Java 中通过 Socket 发送鼠标坐标

Send mouse coordinates over Socket in Java

我一直在网站上四处寻找和搜索,但找不到任何可以回答我问题的内容,如果您认为有一个可以回答我的问题,那么我很抱歉,请做 link 它 =) 无论如何,这里是:

我正在尝试通过套接字将鼠标坐标从客户端发送到服务器。现在我可以通过 DataOutPutStream 发送一个整数,并不断更新它,但是鼠标坐标当然有 2 组数据,x 和 y。

所以我的问题是,如何发送多个数据,服务器如何知道哪个是x哪个是y?

正如您在我的客户端中看到的那样,我正在发送一个值为 5 的 int,但我需要能够发送 x 和 y,然后能够区分来自服务器的 2-边,并使用它们。

这是我的客户发送 atm 的内容:

package com.company;

import java.io.*;
import java.net.Socket;

/**
 * Created by John on 20/04/2015.
 */
public class Client implements Serializable{


public static void main(String[] args) throws IOException {
    Socket s = new Socket("localhost",1234);
    int testX = 5;


    DataOutputStream out;

    out = new DataOutputStream(s.getOutputStream());

    while(true) {
        out.writeInt(testX);

    }

}

}

这是服务器:

package com.company;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server{

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        ServerSocket server = new ServerSocket(1234);
        Socket s = server.accept();
        DataInputStream in;
        in = new DataInputStream(s.getInputStream());




        while(true) {
            Thread.sleep(10);
            System.out.println(in.readInt());
        }
    }
}

如果有人可以解释或将我重定向到可以帮助我解决这个问题的地方,我将不胜感激!

祝你有愉快的一天=)

您可以改用 ObjectOutputStream 并在客户端使用它。 创建一个包含两个整数坐标的 class MouseCoordinate 并通过 ObjectOutputStream 发送此 class 的一个实例。

在服务器端,您需要一个 ObjectInputStream 来接收对象,以及您创建的 class。

所以在你的客户端,替换

public static void main(String[] args) throws IOException {
    Socket s = new Socket("localhost",1234);
    int testX = 5;


    ObjectOutputStream out;

    out = new ObjectOutputStream(s.getOutputStream());

    while(true) {
        out.writeObject(new MouseCoordinates(testX,testY));
      // Unshared prevents OutOfMemoryException
      //out.writeUnsharedObject(new MouseCoordinates(testX,testY));


    }

}

并在您服务器的主要方法中:

ServerSocket server = new ServerSocket(1234);
Socket s = server.accept();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());

while(true) {
  MouseCoordiate coord = (MouseCoordinate) in.readObject();
  // Or use unshared variant as in client:
  // MouseCoordinate coord = (MouseCoordinate) in.readUnsharedObject();
  System.out.println(coord);
  // do something with coordinate...
}

编辑: 您的 MouseCoordinate class 需要实现 Serializable 接口。

编辑#2: 如果你遇到 OutOfMemoryExceptions,你可能需要每隔一段时间重置一次 OutputStream(如 this article 中所述),或者使用 writeUnsharedObject() 及其对应的 readUnsharedObject() 方法ObjectStreams 的数量。

您尝试过使用对象吗?

这是一个例子:

public class Coordinates implements Serializable {

private int x,y;

// include setter and getters
}

并将其发送到服务器而不是 int。

在这种简单的情况下,您可以只写 x 坐标,然后写 y。并相应地阅读它们。 TCP 保证字节序列。