Sockets programming in Java
A socket is one of the most fundamental technologies of computer network programming . It is a way of connecting two nodes on a network to communicate with each other. Socket-based software usually runs on two separate computers on the network, but sockets can also be used to communicate locally (interprocess) on a single computer.
The Java Socket Programming has two sections.
- Java Server Socket Program
- Java Client Socket Program
Java Server Socket Program
The Server Socket Program here is a Java Console based Application . This program act as a Server and listening to clients request from Port No. 8888 .
The next step is to create an infinite loop for monitoring the request from Client's side and replying from server side. When the Server Socket accept a request from the Client side, it reads the data from DataInputStream and also it write the response to DataOutputStream .
Server Socket Example
Java Client Socket Program
The Client is connected to the Port 8888 of the Java Server Socket Program , and the IP Address (Computer Name) of the server machine. Here we give as 127.0.0.1 , because the Server and Client running on the same machine. If the client program running on other machine, then you can give the IP Address of that machine.
When the Java Client program starts , it will connect to the Java Server Socket Program and waiting input from client side. When you type the message it will send to the server and then you can see the reply messages from serverside too.
Socket Client Example
How to run this program ?
When you finish coding and compiled the Server and Client program , first you have to start Java Server Socket Program from DOS prompt (console) , then you will get a message " Server Started..." in your DOS screen, where the server program is running .
Next step is to start Java Client Socket Program in the same computer or other computers on the same network . When you start the client program , it will establish a connection to the Server and waiting input from client side. When you type the message and press ENTER button, then you can see the same message on server side. After receiving message from client side, you can send message to client from server side. When the client send "bye" from client side the server closes the connection from client.