ObjectInputStream不适用于套接字

时间:2014-03-01 11:47:07

标签: java sockets input stream

几天前,我开始编写一个小型多人游戏代码,我使用ObjectInputStreams和ObjectOutputStreams来与服务器交换数据。但由于某种原因,服务器没有收到任何东西。所以我搜索了一些帮助,但我发现的一切都是,我必须刷新ObjectOutputStream。当然我这样做了,但这不是我的问题的解决方案。所以我写了一个很小的测试应用程序,和我的游戏一样。但是仍然存在同样的问题:InputStream没有收到任何东西。所以这是测试应用程序的代码:

服务器应用程序:

    try {
        ServerSocket srvr = new ServerSocket(12975);

        Socket client = srvr.accept();

        ObjectInputStream in = new ObjectInputStream(client.getInputStream());
        ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
        out.flush();

        System.out.println("server ready!");

        String line = "";
        while(!line.equalsIgnoreCase("exit")){
            while(in.available() <= 0){}
            line = in.readObject().toString();
            System.out.println(">>> recieved: " + line);
        }

        client.close();
        srvr.close();
        System.exit(0);
    } catch (IOException e) {
        System.err.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

这是客户端应用程序:

    try {
        Socket client = new Socket("localhost", 12975);

        ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
        out.flush();
        ObjectInputStream in = new ObjectInputStream(client.getInputStream());

        System.out.println("client ready!");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

        String line = "";
        while(!line.equalsIgnoreCase("exit")){
            System.out.print("> ");
            line = input.readLine();
            out.writeObject(line);
            out.flush();
        }

        client.close();
        System.exit(0);
    } catch (IOException e) {
        System.err.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }

我尝试向双方执行此操作:服务器 - &gt;客户端和客户端 - >服务器,但两个套接字都没有收到任何内容。任何研究都失败了,因为在构造OutputStream之后,每个人似乎都忘记了flush(),但它确实有效。 所以我希望,任何人都知道这个问题并能够帮助我。

P.S:我不是来自英国,也不是来自美国,很抱歉,如果我的英语包含错误! :d

1 个答案:

答案 0 :(得分:0)

试试这个,这是有效的。

while(!line.equalsIgnoreCase("exit")){
    while(in.available() <= 0){
        line = in.readObject().toString();
        System.out.println(">>> recieved: " + line);
    }
}

您在服务器代码中错误地使用了第二个 while 循环括号。