nikhil1231
nikhil1231

Reputation: 79

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:

What doesn't:

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.

Upvotes: 0

Views: 1398

Answers (1)

Kayaman
Kayaman

Reputation: 73528

Both your client and server are waiting for the other side to start communicating.

Upvotes: 1

Related Questions