Building Java Client/Server Applications with TCP. Part 4

Building Java Client/Server Applications with TCP. Part 4

The greeting client-server program

 

We’ll also present a greeting program, that emulates a communication protocol between a client and a server.

 

The server will start on a given port and wait for the connection of a client. It will read the greeting of the client and answer to it. This is how the server code looks like:

 

greeting client-server program 1.JPG
greeting client-server program 2.JPG

 

In order to use this program, you have to pass one argument to it: the port.

 

The client will start and try to connect to a given server on a given port. It will send a greeting to the server, receive the answer, then stop its execution. This is how the client code looks like:

 

client code.JPG

 

In order to use this program, you have to pass two arguments to it: the server and the port.

 

This is the result of running these programs with the argument “6066” on the sever side and with the arguments “localhost 6066” on the client side.

 

localhost 6066.png

 

The server side

 

localhost 6066 client side.png

 

The client side

Interested in Java?

Check out our trainings

 

Conclusions

 

Java provides a convenient API to build client-server applications. We have started with explanations regarding the functionality of the TCP protocol, then moved to the introduction of the essential Java socket classes. We have presented two simple programs that use sockets: the port scanner and the greeting client-server program. The principles of communication trough TCP from Java are embedded into these examples. From here, one can build his own applications that use a particular communication protocol.

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning