Building an Echo server

A recipe (for success (ish))

Codeidoscope
8 min readDec 31, 2018

Ingredients:

  • A port and an IP address
  • A server socket
  • A client socket
  • A connection that can be accepted (and closed)
  • Input and Output Streams
  • An input loop

What’s an echo server?

For now, I will leave you to dig for the really technical details of what an echo server is, and instead will tell you more about what it does and how it does it. An echo server is a programme that sends you back the same message you just sent it. For it to work, you will need a client, and a server. The client is what will send the message, and where you will see the response appear. The server receives the message and sends it back to the client.

The recipe:

Step 1 — Opening a connection

Your echo programme does not need to be connected to the Internet to run and work, so what does it mean to open a connection? You will need to create a server socket that will connect to a given port, and listen to messages sent to that port. Wait what? What’s a socket? What’s a port?

A socket is (my least favourite word ever) an endpoint. It’s like a little gate out of which come things and out of which other things leave. Imagine two adjacent fields — one with sheep, another with no sheep. The gate that you open to let the sheep in the sheepless field is a socket.

The port is how you indicate which specific field you want to let your sheep in. If the first field your sheep are in is a square field with four adjacent fields, and you needed to let your farmer friend which one they should go in next, you’d give him the location of the field. That’s what the port is.

As you create your socket, you need to bind it to a port. There’s a bunch of port that you can use on your local computer, and a common one you will see is 8080. The reason you need to bind your socket is so that it knows where to direct its attention and where to listen from.

The next step is for your socket to accept a client connection. If a client connects to the same port that your server is listening on, the connection should be accepted.

Other step 1— Connecting to the server’s port and local address

I promise I can count, but these steps are concurrent, so bear with me. In order for your server to accept a connection, you need to create a client connection for it to accept.

I will not talk about the creation of a client in this post, simply because I haven’t had to do it. I used telnet and netcat as my clients for my echo server project. Both allow you to create a client socket that takes the address of the machine you want to connect to, and the port you want to connect to.

Make sure that the port matches the port you chose for your server so that they know about each other. For the address, you can use 0.0.0.0 or 127.0.0.1, which have subtle differences but should create a connection on your machine.

Step 2 — Opening Input and Output Streams

Yeah I feel you, you keep reading words that don’t make sense, I know. I’m sorry. Thankfully, we can afford to be quite literal here. These streams are flows of data that go in one direction (input) or another (output). An input stream, in this specific context, is the flow of data that goes from the client to the server. The output stream is the reverse, going from the server to the client.

This is where it gets tricky, because there are a couple of loops that will need to run in your programme, but I will tackle those later. Just remember that you need to open these two lil’ guys other you’re not gonna be able to write or print anything.

On my diagram, I’ve mentioned setting up a flag to check if the server should still be running. This is one possible way to ensure that your server does not disconnect when your client does.

Step 3 — Start an input loop
Step 4 — Sending a message to the server
Step 5 — Receiving messages from the server

The input loop starts on the server side, and will have the server wait to receive a message from the client before processing it and sending a reply. When you have your server and your client windows running side by side, you will only see the result of your actions in your client window.

You will type a message in your client terminal window, press enter and this will send it to the server, which will then do whatever you’ve told it to with it, before sending the reply back to the client, who will print it to your window.

This loop will continue until you close your client socket (which you can do by exiting out of the programme or the window).

Step 6 — Disconnecting the client

Once you’ve had your fun writing stupid things into a window and seeing it being printed back at you, you can just exit the programme or the window. If you’ve set up that loop I was talking about earlier that I said I would talk about later, your server will remain open and waiting to accept a new connection.

Step 7 — Closing the server connection

Two options here: Either you did set up that flag earlier and you connection will close as your loop breaks, or you just exit out of the programme.

If you did not just exit the programme and instead had your loop break, closing the connection this will involve closing your input stream, your output stream, you client socket and your server socket in that order, before exiting the programme.

The loops

I love loops. Not. But they’re kind of useful, so let me tell you a little about the ones I have in place for this project. They work just like Russian dolls, with one running within the other, so I’m going to talk about the first one first (yes, I know, my writing skills are magnificent on a 31st December after two weeks of thinking about things that are not code, sorry for that).

The connection loop

This first loop that needs to be implemented is optional, depending on what exactly it is that you need your server to do, and what behaviour you have in mind for it. In my case, I needed to be able to keep the server open and accept different client connections (these did not need to be simultaneous, so I did not focus on that).

In order to keep my server alive while my client was connecting/disconnecting, I decided to use Java’s do while loop, and implement a flag to break the loop when needed. This is neither the optimal nor the only way of implementing a while loop, so find what works for you.

    Create the server socket by giving it a port number
do {
Accept the client socket connection
Open the Input and Output streams
Input Loop (this is where the flag is set to false)
} while (flag is true);
Close the server socket connection

The first step in this pseudo-code snippet is to create the server socket by giving it a port number. I’ve given more information about what that is earlier on, but make sure that your loop is implemented after you create this connection, otherwise god knows how your code will explode because that flag is not readable outside the loop and your programme will complain that it doesn’t exist. So yeah, create that server socket before.

Within the while loop, you accept the client connection, open the streams and implement the second loop, which I will tackle later on: the input loop. Incidentally, this is where the flag that breaks the while loop of the connection loop is set. Until the user on the client side sets it as false by entering a command of your choice, the loop will keep running.

This means that your server is running all this time as you have not told it to shut down, which allows you the open and close client connections as you please. Once you’ve set the flag as false, it exits the loop and closes the server connection (this will also close the client connection if you hadn’t done that before as it cannot exist without the server connection).

The input loop

The second loop is, as I mentioned, the input loop. This one needs to live inside the client connection loop. I have implemented it as a try/catch so that I could more easily handle exceptions (I think — it’s been a while since I looked at my code).

Create the server socket by giving it a port number
do {
Accept the client socket connection
Open the Input and Output streams
try {
User input loop
} catch {
Throw exception
}
} while (flag is true);
Close the server socket connection

Within that try/catch statement is a method that is executed when the programme hits the try statement, let’s look at it in more depth:

    while the input line is not null {
if the input line equals "off" {
Set the flag to false
}
Send the input line to the client
}

There is a little more complexity that what I’ve pseudo-coded here, but this is the rough recipe for what you will need. As long as the input line is not null (bearing in mind that spaces and new lines do not count as null), it checks if the input is equal to “off”, which is how I implemented the setting of my flag, and which you are entirely free to disregard or update as you please.

If the input is not equal to “off”, then it sends back the input line to the client. At this point, I’ve implemented my own validation and manipulation because I needed my server to send back “echo” if the user inputs “echo”, “polo” if they input “Marco”, and nothing if they input anything else.

And with this, you should be able to get an understanding of how an echo server can work, and how to implement your own server! I’m hoping to spend more time writing about Input and Output streams, as well as other components of clients and servers that I’ve come across, so keep an eye out for those (maybe…)

--

--