将鼠标坐标等发送到服务器

时间:2013-08-18 16:31:25

标签: java networking

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

客户代码

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

CustomObject

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

1 个答案:

答案 0 :(得分:1)

你没有说它是如何起作用的,但可以立即发现的是你没有读到与你所写的相同的东西:

你写的是什么:

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

你读到了什么:

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

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

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

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