Chat Program Java is a continuous communication between two systems. Networking chapter also (apart threads, DS etc.) proves that Java language is simple to develop applications that are difficult (requires extra practice and experience) in other languages.
Before going into the details of client-server communication, it is advised to go through Networking – Introduction and Communication with TCP/IP Protocol to know the terms and basics of networking and the way Java supports.
Total 4 programs are given in TCP/IP protocol based communication.
Application Number | Functionality |
---|---|
1st application | Client to server communication (one-way) |
2nd application | Server to client communication (one-way) |
3rd application | Server sends file contents to client (two-way, non-continuous) |
4th application | Chat program (two-way, continuous) |
4th application – Chat Program Java: Chat communication (two-way continuous)
This is the last one of the four series where client and server talks continuously until one disconnets.
Chat communication is the process of exchanging messages between two systems continuously. Anyone can break the communication. Both systems come with the following same responsibilities.
- Reading from keyboard. Uses an input stream like BufferedReader connected to System.in.
- Sending data to the other system what is read from keyboard. Uses an output stream like PrintWriter connected to getOutputStream() method of Socket.
- Receiving data from the other system. Uses an input stream like BufferedReader connected to getInputStream() method of Socket.
As the responsibilities are same, both client and server programs contain the same stream objects and same code. The order of using stream objects varies in the while loop.
Client program: GossipClient.java
import java.io.*;
import java.net.*;
public class GossipClient
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
}
}
}
Note: To come out of the chat, type Ctrl+C.
Server program: GossipServer.java
import java.io.*;
import java.net.*;
public class GossipServer
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock = sersock.accept( );
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;
while(true)
{
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}

Screenshot on Chat Program Java
pwrite.flush();
The flush() method of PrintStream class flushes any uncleared buffers in memory. Generally when the streams are closed, the buffers are pushed out of all the data contained in. But, in the program no stream is closed; so, it is necessary to flush the data explicitly with flush() method.
As you can observe, both programs are using same streams and objects. The difference comes in while loop. Client sends first and then receives where as server first receives and then sends. The other terms of the code are explained in the earlier three applications.
Do you know?
1. A frame can be created without a border.
2. Coffee cup on the frame title bar can be changed with your photo.
3. Size of the button depends on the layout manager you choose.
4. The space along the border of the frame and components inside can be adjusted.
5. Java support freelance drawing using AWT.
6. Components can be added without using layout manager.
7. Dialog box can be modal or modeless.
8. There exists HeadlessException in AWT.
9. You can draw a cube, cylinder etc. without having predefined methods.
10. addActionListener() is a method of Button but not ActionListener.
11. Importing both java.awt and java.awt.event
can u plz tell me how cmtrl+c working in the code
sir i need implmention chat server with scoket application plz help out program should be in python language.
Thankyou
what additional features can we add on this ?
hello sir
give the output of GossipClient & GossipServer class
give output of GossipClient & GossipServer class
Thanks a lot, the code is compact and works like a charm, perfect to modify and reuse.
how to create a chat program
On a single system, open two DOS prompts, treat one as client and the other as Server. First run server program.
How to start in cmd what is the cmd for that when i run using java GossipSever class not found exception occur
Sir,
if we run server program in one machine and client program in another program where computer are connected in LAN.
than this program works or it needs any modification.
They are connected through system. To do this, no modification is not required.
sir,how to implement socket program between two or more different systems. what is required in program
I gave between two, implement in the same way.
im not able to run this code in eclipse. can you please help me out to fix this problem.
Open two users in the same project space..
What do you mean? Could you elaborate more!
How about a multi-user version of chat?
This is not discussed here in this tutorial.
It is not given here. To be planned.
//MultiClient-Server
//MServer
import java.io.*;
import java.net.*;
class MServer implements Runnable
{
ServerSocket ss;
public void run()
{
String name = Thread.currentThread().getName();
while(true)
{
try{
System.out.println(“Client “+name+” ready to accept…”);
Socket s = ss.accept();
System.out.println(“Client “+name+” accepted the connection”);
BufferedReader readKb = new BufferedReader(new InputStreamReader(System.in));
PrintStream writeC = new PrintStream(s.getOutputStream(), true);
BufferedReader readC = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msgFromC, msgToC;
while(true)
{
if((msgFromC = readC.readLine()) != null)
System.out.print(“\nClient “+name+” : “+msgFromC+”\n\nYou : “);
msgToC = readKb.readLine();
writeC.println(msgToC);
writeC.flush();
}
}
catch(Exception e) { }
}
}
public static void main(String[] args)
{
try {
MServer ms = new MServer();
ss = new ServerSocket(156);
Thread t1 = new Thread(ms, “One”);
Thread t2 = new Thread(ms, “Two”);
t1.start();
t2.start();
}catch(Exception e) { }
}
}
//MClient
import java.io.*;
import java.net.*;
class MClient
{
public static void main(String[] args)
{
try {
Socket s = new Socket(“localhost”, 156);
BufferedReader readKb = new BufferedReader(new InputStreamReader(System.in));
PrintStream writeS = new PrintStream(s.getOutputStream(), true);
BufferedReader readS = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(“You may begin chatting :\n”);
String msgFromS, msgToS;
while(true)
{
msgToS = readKb.readLine();
writeS.println(msgToS);
writeS.flush();
if((msgFromS = readS.readLine()) != null)
System.out.print(“\nServer : “+msgFromS+”\n\nYou : “);
}
}catch(Exception e) {}
}
}
can you give explanation for the above program
Sir,
Can u tell me how to run the Client and Server Program…
Thanks for your help..
First run server program and then client program.
Open two DOS prompts, treat one a server and the other client.
This example should use pwrite.flush() instead of System.out.flush().
Hello sir,
When i run this programs in two command prompts i didnt get messages in server, whatever i typed in client console. how to run this properly
R.Vithu
First run always server program from one prompt. Then type from other DOS prompt the client program. First conversation should be started by client, then server, then client like this. Do not type two times and press enter at a single DOS prompt. Then you have to close the prompt and restart again.
Dear sir,
When I am trying the program in local host I am unable to send multiple messages till I get reply from server. Please can say me the program to communicate without interruption.
both of them should receive messages without any reply also.
The code demands one by one. If client or server types two times continuously, the program does not work. You have to modify the code.
in d 4th program hw to tok to multiple client is missing!!!!!!
The program is designed to for a single client.
This chat program(4Th example) is unable to connect multiple clients. How to connect multiple clients to a single server? – See more at: http://way2java.com/networking/chat-program-two-way-communication/#sthash.RyYhKPQK.dpuf
The program is designed to for a single client.
This is a program for server that can talk with multiple client :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ChatApp;
import java.io.*;
import java.net.*;
public class ChatServer implements Runnable
{
Socket sock;
int ID;
public static void main(String[] args) throws Exception
{
int count=0;
try{
ServerSocket sersock = new ServerSocket(19999);
System.out.println(“Server ready for chatting”);
while (true) {
Socket sock = sersock.accept();
Runnable runnable = new ChatServer(sock,++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
catch(Exception e){}
}
ChatServer(Socket s, int i) {
this.sock = s;
this.ID = i;
}
@Override
public void run() {
try{
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;
while(true)
{
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
catch(IOException e1)
{
System.out.println(e1);
}
catch(Exception e2)
{
System.out.println(e2);
}
}
}
and for client side code remain same…have fun…
if we uses BufferReader and BufferWriter in client as well as server side(for 2 way connection BUT 1 RESPONSE FROM BOTH) y it dont work becoz both are high stream and high stream can go to high stream
and one more problm which i saw that if you put buffer reader in server side and buffer writer in the client side then it show null value in the server and show socket close problm in the client side y this happen u can even check the below codes
please answer
for server
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
System.out.print(“Server started”);
ServerSocket ss= new ServerSocket(5000);
Socket so=ss.accept();
System.out.println(“client connected”);
DataOutputStream dos=new DataOutputStream(so.getOutputStream());
BufferedReader din= new BufferedReader(new InputStreamReader(so.getInputStream()));
BufferedReader b1= new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Entr msg”);
String str=b1.readLine();
dos.writeUTF(str);
System.out.println(“your msg” + din.readLine());
dos.close();
din.close();
b1.close();
}
}
for client
import java.net.*;
import java.io.*;
class Client
{
public static void main(String…aa) throws Exception
{
InetAddress inet= InetAddress.getLocalHost();
Socket so= new Socket(inet,5000);
DataInputStream din=new DataInputStream(so.getInputStream());
BufferedWriter dos =new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
BufferedReader b1= new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Entr msg”);
String str=b1.readLine();
dos.write(str);
System.out.println(“your msg” + din.readUTF());
din.close();
dos.close();
b1.close();
}
}
Good work. Choose GUI TextArea and TextField. All the problems will be solved.
but why these problm coming…
i am trying only one response from both i.e. client and server but the code for server of mine is not working can you help me whats the problm with the code
import java.net.*;
import java.io.*;
class server
{
public static void main(String…aa) throws Exception
{
InetAddress inet= InetAddress.getLocalHost();
ServerSocket ss= new ServerSocket(5000);
Socket so=ss.accept();
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
OutputStream os=so.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
InputStream is=so.getInputStream();
BufferedReader br1= new BufferedReader(new InputStreamReader(is));
String str=br.readLine();
bw.write(str);
bw.flush();
System.out.println( br1.readLine());
}
}
and this is client side code for the above server code
import java.net.*;
import java.io.*;
class client
{
public static void main(String…aa) throws Exception
{
InetAddress inet= InetAddress.getLocalHost();
Socket so= new Socket(inet,5000);
BufferedReader bw= new BufferedReader(new InputStreamReader(System.in));
OutputStream is1=so.getOutputStream();
PrintWriter bw1= new PrintWriter(is1,true);
InputStream is=so.getInputStream();
BufferedReader br= new BufferedReader(new InputStreamReader(is));
System.out.println(br.readLine());
String str=bw.readLine();
bw1.println(str);
System.out.flush();
}
}
the same ques is mine too is it possible to connect to many clients and if yes then how becoz here server and one client is in communication untill connection will not b cutted next client cant make connection
There is an implicit algorithm in OS when two clients ask the same port number, the OS allocates different port number for other client (this is transparent to the client).
This chat program(4Th example) is unable to connect multiple clients. How to connect multiple clients to a single server?
i like the 4th example, would be good if server allowed for multiple clients to talk to server