我一直在网站上四处寻找和搜索,但找不到任何可以回答我问题的内容,如果您认为有一个可以回答我的问题,那么我很抱歉,请链接它 =) 无论如何,这里是:
我正在尝试通过套接字从客户端向服务器发送鼠标坐标。现在我可以通过 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相反,并在客户端使用它。 创建一个包含两个整数坐标的 MouseCoordinate 类,并通过 ObjectOutputStream 发送此类的实例。
在服务器端,你需要一个 ObjectInputStream接收对象,以及您创建的同一类。
所以在你的客户端,替换
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 类需要实现 Serializable界面。
编辑#2:
如果遇到 OutOfMemoryException
,您可能需要每隔一段时间重置一次 OutputStream(如 this article 中所述),或使用 writeUnsharedObject()
及其相应的ObjectStreams 的 readUnsharedObject()
方法。
关于java - 在 Java 中通过 Socket 发送鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768246/