【问题标题】:Java socket does not receive dataJava 套接字不接收数据
【发布时间】:2013-11-21 20:50:59
【问题描述】:

我必须编写从客户端请求问题并接收答案的服务器应用程序。这是我的客户代码:

clientSocket = new Socket("localhost", 1234);
        System.err.println("Client started");
//get questions
        ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
        Question q = (Question)in.readObject();
//send answer
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
        out.print("a1");
        out.flush();

和服务器代码:

//sending questions
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
        List<Question> quest = Questions.getInstance().getQuestions();
        out.writeObject(quest.get(0));
        out.flush();
    //get answer
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String temp = null;
        while ((temp = in.readLine()) == null) {}
        String answer = temp;

客户端成功发送并稍后接收问题,但服务器从未得到答案(读取临时变量时无限循环)。有什么问题?

【问题讨论】:

  • 您在客户端调用out.print("a1");,但使用in.readLine() 在服务器上读取一行。你不应该在客户端使用println() 写出来,否则服务器永远不会到达行尾?
  • 很确定这是问题所在...为什么不将其发布为答案,这样它就不会出现在未回答列表中...?

标签: java sockets


【解决方案1】:

你的呼唤.print("a1");在客户端上,但使用 in.readLine() 读取服务器上的一行。您不应该在客户端上使用 println() 写出,否则服务器永远不会到达行尾? – CodeChimp 11 月 21 日 21:07

感谢 CodeChimp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2020-09-24
    • 2012-04-23
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多