使用PrintWriter无法工作通过Java套接字发送数据

时间:2015-08-18 12:49:05

标签: java sockets io stream

我目前正在学习使用Java中的套接字,但无法管理套接字之间的数据,在这种情况下,在Android和计算机之间,如果这是相关的。我使用的方法来自here

请原谅糟糕的代码格式。

客户端:

PrintWriter out = null;
    try {
        Socket socket = new Socket("IP_OF_SERVER", 8000);

        out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while ((fromServer = in.readLine()) != null) {
            response = fromServer;
            System.out.println("Client: " + fromUser);
            out.println(fromUser);
        }

        socket.close();

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        out.close();
    }
...
textResponse.setText(response);

服务器端:

Socket hostThreadSocket = serverSocket.accept();
...

        PrintWriter out = null;
        String response,inputLine,outputLine;
        try {
            out = new PrintWriter(hostThreadSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(hostThreadSocket.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                outputLine = "Hello";
                out.println(outputLine);
            }


        } catch (IOException ex) {
            Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("IOException");
        }finally{
            try {
                System.out.println("closing socket");
                out.close();
                hostThreadSocket.close();
            } catch (IOException ex) {
                System.out.println("Other IOException");
               Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

什么有效:

  • 在任何一个Java文件中都没有发现错误(据我所见)

  • 建立连接

什么不是:

  • 两端都没有留言

我试图尽可能少地包含代码,如果需要更多代码,我将编辑问题。任何有关修复或调试此问题的帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的客户端和服务器都在等待另一方开始通信。