Java Socket waiting for UTF8

I am trying to implement a client-server application by myself. Its working so far, except the fact, that when I am accessing the port via another application (e.g. Web-Browser) the server application is blocking.

Is there any easy way/good practice to check, if the connecting application is the "client application"?

Here is an short example for a socket listening to port 8080. The socket awaits 2 Strings. If you now connect with the browser (localhost:8080) the connection gets established, but is waiting for the first UTF8.

public class MainSocket {

public static void main(String[] args) {
    ServerSocket serverSocket;
    try {            
        serverSocket = new ServerSocket(8080);
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Connection established");
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                System.out.println(in.readUTF());
                System.out.println(in.readUTF());
                in.close();
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
Jon Skeet
people
quotationmark

You're calling DataInputStream.readUTF8. That expects data like this:

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

(etc)

In other words, this isn't just UTF-8. It's a slight variation on UTF-8 with a length prefix. That's not what a browser is going to write to the connection. Basically, DataInput and DataOutput are symmetric but not entirely general-purpose - they're usually used together, with one side reading via DataInput what the other side has written with DataOutput.

If you just want to read lines of UTF-8, you can use:

try (Reader inputReader = new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(inputReader)) {
    System.out.println(read.readLine());
    System.out.println(read.readLine());
}

(Now it's not at all clear that you should expect a browser to write UTF-8 to the socket either, but the above is more likely to get you to the next step, I'd say...)

people

See more on this question at Stackoverflow