Monday 22 July 2019

Client Server chat program (application) in Java using Socket Programming


                      In this post, we will see Client Server chat program (application) in Java using Socket Programming.
                     
                      Go through the following programs.


Note: First run ChatServer.java and then ChatClient.java in another terminal tab/window.




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

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

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

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

while(true)
{
sentenceFromClient = inFromClient.readLine();

System.out.println("FROM CLIENT: " +sentenceFromClient);

sentence = inFromUser.readLine();

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

}
}
}
 


  

Output (ChatServer.java)
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac ChatServer.java
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java ChatServer
ServerSocket awaiting connections...
Connection from Socket[addr=/127.0.0.1,port=48044,localport=7021]
FROM CLIENT: Hi
Hello
FROM CLIENT: How are you?
I am fine. What about you?
FROM CLIENT: I am also fine. See you soon.




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

Socket clientSocket = new Socket("localhost", 7021);
System.out.println("Connected to Server. Start Chatting with Server:");

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer =new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

while(true)
{
sentence = inFromUser.readLine();

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

sentenceFromServer = inFromServer.readLine();

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

}
}
}

  


Output (ChatClient.java)
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac ChatClient.java
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java ChatClient
Connected to Server. Start Chatting with Server:
Hi
FROM SERVER: Hello
How are you?
FROM SERVER: I am fine. What about you?
I am also fine. See you soon.



 

No comments:

Post a Comment