Monday 22 July 2019

TCP Client Server Program in Java (Socket Programming)


                      In this post, we will see TCP Client Server Program in Java (Socket Programming).
                      TCP is connection oriented protocol. Here, first we have to establish connection between Client and Server and then we can send/receive messages. 

Watch following video to get explanation of this program:


                      Go through the following programs.


Note: First run TCPServer.java and then TCPClient.java in another terminal tab/window.


Program (TCPServer.java)
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(7006);
System.out.println("ServerSocket awaiting connections...");

while(true)
{
Socket connectionSocket = welcomeSocket.accept();
System.out.println("Connection from " + connectionSocket);

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

}
}
}
 


  

Output (TCPServer.java)

parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac TCPServer.java
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java TCPServer
ServerSocket awaiting connections...
Connection from Socket[addr=/127.0.0.1,port=58292,localport=7006]




Program (TCPClient.java)
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;

Socket clientSocket = new Socket("localhost", 7006);
System.out.println("Connected to Server. Enter any message:");

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();

DataOutputStream outToServer =new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

outToServer.writeBytes(sentence + '\n');

modifiedSentence = inFromServer.readLine();

System.out.println("FROM SERVER: " +modifiedSentence);

clientSocket.close();
}
}
  


Output (TCPClient.java)
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac TCPClient.java
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java TCPClient
Connected to Server. Enter any message:
Hello
FROM SERVER: HELLO



 

No comments:

Post a Comment