1. Create a connection that can be connected to.

1. Create a connection that can be connected to.

Java has a plethora of useful networking libraries at your disposal. In this article, I?ll show you how to make a simple Java Server, that will run on your computer. Our Server will do a few things. The moment we connect, it shall print the string ?Hello!?, it shall also give us the option to terminate a connection by typing in ?Peace?. The goal of this tutorial is to show you some useful Java libraries that can make this happen! When it comes to creating a server, there are really 4 mains steps to consider.

Before implementing the core details of the server, we need to find a way of identifying how we shall connect to the server. This is important as it introduces three core networking concepts; ip-address, ports and sockets. Don?t be afraid of these terms, I do my best to explain them below.

IP Address ? In its simplest form, an IP address is just a fancy way of representing the address of a particular computer in a network. This is represented by a particular number e.g It is a unique id, that all other machines in the internet can identify your computer by. In our case, we will run our server on our machine, meaning the connection won?t have to go through the internet and back to our machine, instead the OS is smart enough to route the request within our machine without interacting with the network. For this case, there is a special ip-address dedicated to this; or sometimes coined localhost. In a Linux terminal if you type ip address you will see a list of network devices on your machine. The first one is the loopback device, this device allows any service in your computer to communicate with other services in your machine, your OS will use the loopback address to route it within your machine instead of sending it across the network.

Ports – Once we have the address of the computer in question, we need to be able to connect to the service we want on that computer. This is where ports come in. Ports are like processes that run on a computer that provide some service, so it is important once you?ve identified the correct computer (using the ip address), we must select the port in order to connect to the correct service in that computer.

Sockets -So far we can locate a computer in a network/internet using the ip address. We can identify which service in the computer we want to connect to using the port, however we still need to set up a connection between one computer and our intended computer. This is where sockets come in. Sockets enable full two-way communication between two computers in a network. As you?d expect, sockets require the address and port of the target computer in order to create a connection

Now that we have a grasp on the fundamentals of networking, lets create the server! Let?s begin by creating a connection. Remember connections are created using Sockets.

EC-1: Creating a connectionpublic static void connectToServer() { try(ServerSocket serverSocket = new ServerSocket(9991)) { Socket connectionSocket = serverSocket.accept();

In EC-1, we create a method connectToServer, in this method we have an incomplete-try statement that does the following:1. Creates a ServerSocket2. Specifies the port 9991 that this service will run on3. Accepts the ServerSocket connection!

and Shazam! We have created our connection, well atleas the foundations of the connection. We haven?t connected to anything just yet. In Java, a ServerSocket simply waits on a connection, once connected, receives some arbitrary input, processes that input, then spits back a response! In our case our server will just echo out whatever you choose to type into it! As per the definition of the ServerSocket, it needs to wait on a connection, in EC-1 the last line accepts that connection and we save that in a variable called connectionSocket that is of type Socket .

Awesome so we are done laying the framework for a connection. Let?s make our server interactive by allowing it to communicate back when we connect!

2. Making our Server Interactive

In order to interact back and forth with our server, we need a way to channel information to and fro using our connection we just setup in EC-1. One great way to do this is to use IOStreams, in our case Java?s InputStream and OutputStream classes. These will allow for two-way communication to and from the server. Let?s implement this beneath what we have in EC-1

EC-2: Implement IOStream…InputStream inputToServer = connectionSocket.getInputStream();OutputStream outputFromServer = connectionSocket.getOutputStream();

In EC-2, we create an InputStream that takes an input from connectionSocket created above, and we also create OutputStream that gets the output from the connectionSocket . The input stream represents what we shall be sending to the server, so it is the inputToServer, whereas the output represents the output from server.

EC-3: Turning IOStreams into actual usable data…Scanner scanner = new Scanner(inputToServer, “UTF-8”);PrintWriter serverPrintOut = new PrintWriter(new OutputStreamWriter(outputFromServer, “UTF-8”), true);serverPrintOut.println(“Hello! Enter Peace to exit.”);

In EC-3 we take the IOStreams created in EC-2, and use them. We first create a Scanner, the scanner will take in the input to the server and transform it to a form the server can read. We then create a PrintWriter, the PrintWriter will take the output from the server and print it on our screens. Creating both the Scanner and PrintWriter is essential because the IOStreams alone in EC-2 just represent data in transit, they do not print or convert the data into format the server and user understands. In order for us to see that we have connected to the server, the server should inform us by printing Hello! to us upon connection.

To recap, we can now connect to our server (EC-1), send and receive information from the server thanks to IOStreams (EC-2) and can translate the streams into relevant output for both server and user (EC-3).

3. Server Logic

The server is able to do a lot, however it still cant do basic things such as actually print out data to us, or even terminate the connection on client request. We shall implement the logic here.

EC-4: Server Logicboolean done = false;while(!done && scanner.hasNextLine()) { String line = scanner.nextLine(); serverPrintOut.println(“Echo from <Your name Here> Server: ” + line); if(line.toLowerCase().trim().equals(“peace”)) { done = true; }}

In EC-4, we need a way to check if the client is done with the connection. We start by creating a boolean flag called done and set it to false. We then create a while loop that eagerly observes if the done value changes to true, it also checks to see that the Scanner created in EC-3 is still functioning properly and can accept input.

The role of our server is to print back whatever we type to it, the Scanner class checks if there is a new line sent by the user and we use that input as output for the server, prefixed with ?Echo from <Your Name Here> Server: ?.

Lastly we need to find a way to actually terminate the connection upon client request. So if the client types the word ?peace?, the code will change the done flag to true, and the while-loop condition will no longer be satisfied and it will terminate the loop and the application.

4. Putting Everything Together!

So we have now made our simple Hello server, Here is a gist containing all the code in a single method!

5. Connect to the Server!

It?s time to put all our work and run this code.

5.1 How to Connect

  1. Run this Java application server code from your Java IDE, or command-line.

2. In order for you to connect to the server you need a tool that can allow you to do this. On Linux & Mac, feel free to use netcat or telnet or any other connection protocol you would like, if you do not have them google search how to install them on your OS version. For windows, there are several tools as well like winrs. The commands would be as follows

NetCat: This is a popular networking utility for connecting to websites, servers etc.

nc 9991

Telnet: Telnet is an old bi-directional internet connection protocol. It is very simple and will send data across a connection unencrypted. This means you should avoid using it when passing sensitive information. But for this simple example it works.

telnet 9991

Curl: Curl is a bit different, than the two above as it will connect to the server in a web-page format. The disadvantage of this is that it may not be easy to send text directly to curl once connected, therefore you terminating the connection cannot be done by typing in ?bye?.


5.2 Once Connected

Once connected! You should have something that looks like this. 4

Image for post

Feel free to play around and type stuff to it,

Image for post

Close the connection by typing ?peace?

Image for post

As you play with it, try restarting the connection, adding more connections etc. You will notice these important points:1. This server can only handle a single connection, so multiple connections to it will be voided. In a future article we shall make this server concurrent, allowing it to handle multiple connections.2. If the client i.e you, terminate the connection, the socket closes, the connection breaks, and the program ends, meaning you cannot connect to the server again without restarting the application.


The purpose of this article was to play around with some of the cool network features employed by Java! As you can see the possibilities are endless. We could have coded our Server in a way that perhaps performs mathematical calculations based on the input data we provide, or our server could be the intermediary between a database, and it would perform actions like retrieving, verifying, manipulating or sanitizing database information based on input. The opportunities are endless!

Thanks again for reading!Twitter – @martinomburajr

Checkout my other articles on other fun Java concepts

How well do you know the Java main method? 12 simple questions to test your knowledge!

The main method in most programming languages is probably the first method any new developer encounters in their?


Java 8: Default & Static Interface Methods – Similar, but different!

So Java 8 has officially been out for almost 4 years now, and with it came a variety of cool stuff. Some were?


Java 8: Functional Interfaces

Lambda?s have taken over Java, and there is probably no looking back from here. One new primitive introduced to make?



No Responses

Write a response