1

假设我想将鼠标坐标与其他内容一起发送到服务器。最好的方法是什么?我的想法是创建一个对象并将数据附加到它并发送它。如您所见,我已经发布了我的尝试:(它不起作用。)这是一个好方法吗?我究竟做错了什么?等等。如果这不是一个好主意,我应该怎么做呢?

客户端代码

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 );
        }
    }
}
4

1 回答 1

1

您没有说它是如何不起作用的,但是可以立即发现的是,您阅读的内容与所写的内容不同:

你写什么:

while (true) {
    out.writeByte(1);
    out.writeObject(new CustomObject());
    out.flush();
}

你读到的:

while (true) {      
    go = (CustomObject) in.readObject();
    System.out.println( go.mouseX );
}

所以,停止发送这个未使用的字节,它可能会更好地工作。

哦,正如@boowed__l 的评论中所指出的,CustomObject 必须实现 java.io.Serializable 才能可序列化。

如果您有其他问题,请发布您获得的异常的堆栈跟踪。如果您没有得到任何结果,请准确解释发生了什么。

于 2013-08-18T16:35:55.613 回答