简体   繁体   English

Java套接字不接收数据

[英]Java socket does not receive data

I have to write server application that request questions from client and receives an answer. 我必须编写服务器应用程序,从客户端请求问题并收到答案。 This is my client code: 这是我的客户端代码:

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

and server code: 和服务器代码:

//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;

Questions successfully sent and later received by client, but server never get answer (infinite loop while reading temp variable). 问题成功发送并稍后由客户端接收,但服务器永远不会得到答案(读取临时变量时无限循环)。 What is the problem? 问题是什么?

Your calling out.print("a1"); 你的呼叫out.print(“a1”); on the client, but reading a line on the server using in.readLine(). 在客户端上,但使用in.readLine()在服务器上读取一行。 Shouldn't you be writing out using println() on the client, else the server never gets to the end of the line? 你不应该在客户端上使用println()写出来,否则服务器永远不会到达行尾? – CodeChimp Nov 21 at 21:07 - CodeChimp 11月21日21:07

Thanks for CodeChimp 感谢CodeChimp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM