简体   繁体   中英

Sending Data Through Java Sockets using PrintWriter not Working

I am currently learning to use sockets in Java, but can't manage to send data between a socket, in this case between an android and a computer, if that is relevant. The method I'm using is from here .

Please excuse poor code formatting.

Client Side:

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

Server Side:

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

What Works:

  • No errors are found in either Java file (as far as I can see)

  • A connection is established

What doesn't:

  • No message is seen on either end

I've tried to include as little code as possible, if more is required, I will edit the question. Any help for fixing or debugging this problem would be greatly appreciated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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