假设我想将鼠标坐标与其他内容一起发送到服务器。最好的方法是什么?我的想法是创建一个对象并将数据附加到它并发送它。如您所见,我已经发布了我的尝试:(它不起作用。)这是一个好方法吗?我究竟做错了什么?等等。如果这不是一个好主意,我应该怎么做呢?
客户端代码
import java.io.*;
import java.net.*;
public class Client{
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
clientSocket = new Socket("My ip", 4441);
out = new ObjectOutputStream(clientSocket.getOutputStream()); // Stuff to send to server
in = new ObjectInputStream(clientSocket.getInputStream()); // Stuff server sends
} catch (UnknownHostException e) {
System.err.println("Unknown host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
while (true) {
out.writeByte(1);
out.writeObject(new CustomObject());
out.flush();
}
}
}
自定义对象
public class CustomObject {
public int mouseX, mouseY;
public CustomObject() {
this.mouseX = 10;
this.mouseY = 16;
}
}
服务器
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4441);
} catch (IOException e) {
System.err.println("Could not listen on port");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connected");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
CustomObject go;
while (true) {
go = (CustomObject) in.readObject();
System.out.println( go.mouseX );
}
}
}