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:
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:
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.
The server side
The client side
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.
Interested in Java? Check out our trainings.
Java and Web Technologies Expert