Java Socket Programming - Socket Server, Client example

Welcome to Java Socket programming example. Every server is a program that runs on a specific system and listens on a specific port. Sockets are bound to the port numbers and when we run any server it just listens on the socket and waits for client requests. For example, tomcat server running on port 8080 waits for client requests and once it gets any client request, it responds to them.

Java Socket Programming

A socket is one endpoint of a two-way communication link between two programs running on the network. The socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

In java socket programming example tutorial, we will learn how to write java socket server and java socket client program. We will also learn how server client program read and write data on the socket.

java.net.Socket and java.net.ServerSocket are the java classes that implements Socket and Socket server.

Java Socket Server Example

Java Socket Client

To test java socket programming of server-client communication, first we need to run SocketServerExample class. When you will run socket server, it will just print “Waiting for client request” and then wait for the client request.

Now when you will run SocketClientExample class, it will send a request to java socket server and print the response message to console.

Here is the output of java socket server SocketServerExample program.

Here is the output of Java socket client SocketClientExample program.

That’s all for a quick roundup of Socket programming in java. I hope you can get started with java socket server and java socket client programming.

Reference: Oracle Doc

By admin

Leave a Reply