Search code examples
javasocketsinputstream

ClientSocket NOT listening


Im flabbergasted.

I took code from https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java

for the server. And https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java

for the Client. I made minor changes. Mostly so that there is no back and forth echoing. Rather the Server should constantly with 2 second delays send same string. But I just cant understand why the client isnt working. It sends the Exception message: Couldn't get I/O for the connection to 127.0.0.1 I run the server with: java 6788 and the client with: 127.0.0.1 6788 I tried other ports.

I do this in eclipse so I set the arguments in Runconfiguration before running the classes. I start the server first. I tried in terminal outside of eclipse. Nothing makes it work. Basically, the client should connect to server and output with System.out.println() what the server in turn outputs to the client. But nothing happens. what is wrong?

Client:

import java.io.*;
import java.net.*;

public class EchoClient {
    public static void main(String[] args) throws IOException {

        if (args.length != 2) {
            System.err.println(
                "Usage: java EchoClient <host name> <port number>");
            System.exit(1);
        }

        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);

        try (
            Socket echoSocket = new Socket(hostName, portNumber);
            BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(echoSocket.getInputStream()));

        ) {
            String userInput;

            while (true) {
                System.out.println("recieved: " + in.readLine());
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }
}

Server:

import java.net.*;
import java.io.*;

public class EchoServer {
    public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
        }

        int portNumber = Integer.parseInt(args[0]);
        System.out.println(args[0]);
        InetAddress add = InetAddress.getLocalHost();
        System.out.println(add.getHostAddress());
        try (
            ServerSocket serverSocket =
                new ServerSocket(Integer.parseInt(args[0]));

            Socket clientSocket = serverSocket.accept();     
            PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream());                   

        ) {
            while (true) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                out.println("HELLO!");
            }
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        }
    }
}

Solution

  • As in the comment I eventually found a solution. BufferedReader.readLine() "blocked". When reading from a file it returns a line after reading up to a newline character, if I understand it correctly. But since it was "A steady flow" from server with no newlines, it just kept "reading" and never returned a String.

    I then tried using BufferedReader.read() method, that reads character by character, and returns after each char (thus never blocking). It then prints each character as it arrives, also it listens for a newline being sent from server, and once a read character equals a newline, it then prints a newline instead. Sort of emulating the "read line" behaviour I was expecting from original question.

    Reading part of client:

        while(true) {
            character = (char) reader.read();
            if(Character.isISOControl(character)) {
                System.out.println();
            }
            else {
                System.out.printf("%c", character);
            }           
        }
    

    Sending Part of Server:

    private String message = "HELLO\n";
    ...
    while(true) {
                try {
                    Thread.sleep(2000);
                    writer.write(message);
                    writer.flush();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }