We can send a message to it and it echos back in uppercase.
The first problem with this implementation is that it only receives a message and it closes the connection. Before fixing that let’s understand the classes used.
Java classes
ServerSocket
It’s used for connection-oriented communication.
Key methods:
accept(): listens for a connection to be made and accept it. Blocks until a connection is made
bind(SocketAddress endpoint): binds the socket to an specific IP
close(): closes the socket
In the naive approach the constructor already binds to the port. with-open also takes care of closing the connection once the code has executed.
BufferedReader
A nice class for reading text. It’s efficient and thread-safe.
Key methods:
readLine(): reads a line of text. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), or a carriage return followed immediately by a linefeed.
PrintWriter
It’s used for printing text to an OutputStream. Needs to pay attention regarding the flush behavior. I used println because it adds the line feed automatically.
Responding to multiple messages of the same client
To accept multiple messages it’s necessary to keep reading the input. This can be done with another function and loop/recur:
Again, testing with nc:
This implementation only accepts one client. It also shutdown the server once that client has disconnected.
Multiple clients
To support multiple clients at the same time we can use threads.
This accepts multiple clients but there’s not way to shutdown the server.
Ability to start and stop the server
This is a little more robust and supports multiple clients with multiple messages.
The logs of the server look like this:
I’m not sure if there is a better way to handle closing the connections without try/catch.