Chat Program Two Way Communication Java: S. Nageswara Rao, Corporate Trainer June 8, 2011 36 Comments

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

NETWORKING, TCP/IP PROTOCOL, TWO-WAY COMMUNICATION

Chat Program two way communication Java


S. Nageswara Rao, Corporate Trainer
June 8, 2011
36 Comments

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 FUNCTIONALITY
NUMBER
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-contin
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.
1 Reading from keyboard. Uses an input stream like BufferedReader
connected to System.in.
2 Sending data to the other system what is read from keyboard. Uses
an output stream like PrintWriter connected to
getOutputStream() method of Socket.
3 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
}
}
}
}
1 import java.io.*;
2 import java.net.*;
3 public class GossipClient
4 {
5 public static void main(String[] args) throws Exception
6 {
7 Socket sock = new Socket("127.0.0.1", 3000);
8 // reading from keyboard (keyRead object)
9 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1 // sending to client (pwrite object)
0 OutputStream ostream = sock.getOutputStream();
1 PrintWriter pwrite = new PrintWriter(ostream, true);
1
1 // receiving from server ( receiveRead object)
2 InputStream istream = sock.getInputStream();
1 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
3
1 System.out.println("Start the chitchat, type and press Enter key");
4
1 String receiveMessage, sendMessage;
5 while(true)
1 {
6 sendMessage = keyRead.readLine(); // keyboard reading
1 pwrite.println(sendMessage); // sending to server
7 pwrite.flush(); // flush the data
1 if((receiveMessage = receiveRead.readLine()) != null) //receive from server
8 {
1 System.out.println(receiveMessage); // displaying at DOS prompt
9 }
2 }
0 }
2 }
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2

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();
}
}
}
1 import java.io.*;
2 import java.net.*;
3 public class GossipServer
4 {
5 public static void main(String[] args) throws Exception
6 {
7 ServerSocket sersock = new ServerSocket(3000);
8 System.out.println("Server ready for chatting");
9 Socket sock = sersock.accept( );
1 // reading from keyboard (keyRead object)
0 BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
1 // sending to client (pwrite object)
1 OutputStream ostream = sock.getOutputStream();
1 PrintWriter pwrite = new PrintWriter(ostream, true);
2
1 // receiving from server ( receiveRead object)
3 InputStream istream = sock.getInputStream();
1 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
4
1 String receiveMessage, sendMessage;
5 while(true)
1 {
6 if((receiveMessage = receiveRead.readLine()) != null)
1 {
7 System.out.println(receiveMessage);
1 }
8 sendMessage = keyRead.readLine();
1 pwrite.println(sendMessage);
9 pwrite.flush();
2 }
0 }
2 }
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
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
Live Chat for Slack
Ad
Social Intents
IO Streams Overview Java
way2java.com
Download Cleaner for Mac
Ad
mackeeper.com

Echo Server UDP Example Java


way2java.com

Cloud native monitoring


Ad
Dynatrace
Byte streams vs Character streams
way2java.com

Send File Contents two way communication...


way2java.com
OutputStreamWriter
way2java.com

client and server program in java


client server chat application java
client server model in java
java client server chatprogram
← Server to client Example Java
Send File Contents two way communication Java →
36 thoughts on “Chat Program two way
communication Java”
1 bob 
 August 25, 2016 at 7:45 pm
 
 Thanks a lot, the code is compact
and works like a charm, perfect to modify and reuse.
 
 Reply ↓

2 ragul 
 January 21, 2016 at 3:16 pm
 
 how to create a chat
program
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 January 23,

 On a single system, open two DOS
2016 at 10:07 am

prompts, treat one as client and the other as Server. First
run server program.
 
 Reply ↓ 

3 DInesh 
 December 1, 2015 at 10:53 am
 
 Sir,
4 if we run server program in one machine and client program in
another program where computer are connected in LAN.
5 than this program works or it needs any modification.
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 December 1,
2015 at 5:20 pm
 
 They are connected through system. To do
this, no modification is not required.
 
 Reply ↓ 

6 nagavenkatesh 
 September 24, 2015 at 4:01 pm
 
 sir,how to implement
socket program between two or more different systems. what is
required in program
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 25,
2015 at 1:36 am
 
 I gave between two, implement in the
same way.
 
 Reply ↓ 

7 smithendu 
 September 19, 2015 at 9:03 pm
 
 im not able to run this
code in eclipse. can you please help me out to fix this
problem.
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 21,
2015 at 1:04 am
 
 Open two users in the same project
space..
 
 Reply ↓ 

8 Marcos Azevedo 
 July 28, 2015 at 10:28 am
 
 How about a multi-user
version of chat?
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 August 6, 2015
at 6:13 pm
 
 This is not discussed here in this
tutorial.
 
 Reply ↓ 

B S. Nageswara Rao, Corporate Trainer Post author
 
 August 20,
2015 at 2:53 am
 
 It is not given here. To be
planned.
 
 Reply ↓ 

9 ShashankSM 
 April 24, 2015 at 10:29 am
 
 //MultiClient-
Server
 //MServer
 import java.io.*;
10 import java.net.*;
 class MServer implements Runnable
11 {
12 ServerSocket ss;
 public void run()
13 {
14 String name = Thread.currentThread().getName();
15 while(true)
16 {
17 try{
18 System.out.println(“Client “+name+” ready to accept…”);
19 Socket s = ss.accept();
20 System.out.println(“Client “+name+” accepted the connection”);
21 BufferedReader readKb = new BufferedReader(new
InputStreamReader(System.in));
22 PrintStream writeC = new PrintStream(s.getOutputStream(),
true);
23 BufferedReader readC = new BufferedReader(new
InputStreamReader(s.getInputStream()));
24 String msgFromC, msgToC;
25 while(true)
26 {
27 if((msgFromC = readC.readLine()) != null)
28 System.out.print(“\nClient “+name+” : “+msgFromC+”\n\nYou :
“);
29 msgToC = readKb.readLine();
30 writeC.println(msgToC);
31 writeC.flush();
32 }
33 }
34 catch(Exception e) { }
35 }
36 }
 public static void main(String[] args)
37 {
38 try {
39 MServer ms = new MServer();
40 ss = new ServerSocket(156);
 Thread t1 = new Thread(ms,
“One”);
41 Thread t2 = new Thread(ms, “Two”);
42 t1.start();
43 t2.start();
44 }catch(Exception e) { }
45 }
46 }
 //MClient
 import java.io.*;
47 import java.net.*;
 class MClient
48 {
49 public static void main(String[] args)
50 {
51 try {
52 Socket s = new Socket(“localhost”, 156);
53 BufferedReader readKb = new BufferedReader(new
InputStreamReader(System.in));
54 PrintStream writeS = new PrintStream(s.getOutputStream(),
true);
55 BufferedReader readS = new BufferedReader(new
InputStreamReader(s.getInputStream()));
56 System.out.println(“You may begin chatting :\n”);
57 String msgFromS, msgToS;
58 while(true)
59 {
60 msgToS = readKb.readLine();
61 writeS.println(msgToS);
62 writeS.flush();
63 if((msgFromS = readS.readLine()) != null)
64 System.out.print(“\nServer : “+msgFromS+”\n\nYou : “);
65 }
66 }catch(Exception e) {}
67 }
68 }
 
 Reply ↓ 

69 venu 
 March 2, 2015 at 10:08 am
 
 can you give explanation for the
above program
 
 Reply ↓ 

70 Naresh Kumar 
 September 16, 2014 at 5:33 pm
 
 Sir,
 Can u tell me
how to run the Client and Server Program… 
 Thanks for your
help..
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 16,
2014 at 10:14 pm
 
 First run server program and then client
program.
 Open two DOS prompts, treat one a server and
the other client.
 
 Reply ↓ 

71 Karan Bansal 
 July 30, 2014 at 7:10 pm
 
 This example should use
pwrite.flush() instead of System.out.flush().
 
 Reply ↓ 

72 vithu 
 May 24, 2014 at 9:16 am
 
 Hello sir,
73 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
74 R.Vithu
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 May 24, 2014
at 10:49 pm

 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.
 
 Reply ↓ 

75 msr 
 September 26, 2013 at 6:47 am
 
 Dear sir,
76 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.
77 both of them should receive messages without any reply
also.
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 26,

 The code demands one by one. If client or
2013 at 1:45 pm

server types two times continuously, the program does not
work. You have to modify the code.
 
 Reply ↓ 

78 smarty 
 September 6, 2013 at 10:40 am
 
 in d 4th program hw to
tok to multiple client is missing!!!!!!
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 6,
2013 at 10:27 pm
 
 The program is designed to for a single
client.
 
 Reply ↓ 

79 smarty 
 September 6, 2013 at 10:39 am
 
 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
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 September 6,
2013 at 10:27 pm
 
 The program is designed to for a single
client.
 
 Reply ↓ 

80 RC 
 April 23, 2013 at 2:23 pm
 
 This is a program for server that can
talk with multiple client :
81 /*
82 * To change this template, choose Tools | Templates
83 * and open the template in the editor.
84 */
85 package ChatApp;
 import java.io.*;
86 import java.net.*;
87 public class ChatServer implements Runnable
88 {
89 Socket sock;
 int ID;
90 public static void main(String[] args) throws Exception
91 {
92 int count=0;
93 try{
94 ServerSocket sersock = new ServerSocket(19999);
95 System.out.println(“Server ready for chatting”);
96 while (true) {
97 Socket sock = sersock.accept();
98 Runnable runnable = new ChatServer(sock,++count);
99 Thread thread = new Thread(runnable);
100 thread.start();
101 }
102 }
103 catch(Exception e){}
 }
104 ChatServer(Socket s, int i) {
105 this.sock = s;
106 this.ID = i;
107 }
 @Override
108 public void run() {
109 try{
110 BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
111 // sending to client (pwrite object)
112 OutputStream ostream = sock.getOutputStream();
113 PrintWriter pwrite = new PrintWriter(ostream, true);
 // receiving
from server ( receiveRead object)
114 InputStream istream = sock.getInputStream();
115 BufferedReader receiveRead = new BufferedReader(new
InputStreamReader(istream));
 String receiveMessage,
sendMessage;
116 while(true)
117 {
118 if((receiveMessage = receiveRead.readLine()) != null)
119 {
120 System.out.println(receiveMessage);
121 }
122 sendMessage = keyRead.readLine();
123 pwrite.println(sendMessage);
124 pwrite.flush();
125 }
126 }
127 catch(IOException e1)
128 {
129 System.out.println(e1);
130 }
131 catch(Exception e2)
132 {
133 System.out.println(e2);
134 }
135 }
136 }
137 and for client side code remain same…have fun…
 
 Reply ↓ 

138 v.s. 
 July 25, 2012 at 7:14 am
 
 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
139 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
140 please answer
 for server
 import java.io.*;
141 import java.net.*;
 public class Server {
142 public static void main(String[] args) throws Exception
{
 System.out.print(“Server started”);
143 ServerSocket ss= new ServerSocket(5000);
144 Socket so=ss.accept();
145 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”);
146 String str=b1.readLine();
147 dos.writeUTF(str);
148 System.out.println(“your msg” + din.readLine());
149 dos.close();
150 din.close();
151 b1.close();
152 }
153 }
 for client
 import java.net.*;
154 import java.io.*;
 class Client
155 {
156 public static void main(String…aa) throws Exception
157 {
158 InetAddress inet= InetAddress.getLocalHost();
159 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”);
160 String str=b1.readLine();
161 dos.write(str);
162 System.out.println(“your msg” + din.readUTF());
163 din.close();
164 dos.close();
165 b1.close();
166 }
 }
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 July 25, 2012 at
9:20 am
 
 Good work. Choose GUI TextArea and TextField.
All the problems will be solved.
 
 Reply ↓ 

i v.s. 
 July 26, 2012 at 1:25 am
 
 but why these problm
coming…
 
 Reply ↓ 

167 v.s. 
 July 23, 2012 at 6:08 am
 
 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.*;
168 import java.io.*;
 class server
169 {
170 public static void main(String…aa) throws Exception
171 {
172 InetAddress inet= InetAddress.getLocalHost();
173 ServerSocket ss= new ServerSocket(5000);
174 Socket so=ss.accept();
 BufferedReader br= new
BufferedReader(new
InputStreamReader(System.in));
 OutputStream
os=so.getOutputStream();
175 BufferedWriter bw= new BufferedWriter(new
OutputStreamWriter(os));
 InputStream is=so.getInputStream();
176 BufferedReader br1= new BufferedReader(new
InputStreamReader(is));
 String
str=br.readLine();
 bw.write(str);
177 bw.flush();
178 System.out.println( br1.readLine());
 }
 }
 
 Reply ↓ 

A v.s. 
 July 23, 2012 at 7:26 pm
 
 and this is client side code for the
above server code
 
 Reply ↓ 

i v.s. 
 July 24, 2012 at 1:54 am
 
 import java.net.*;
ii import java.io.*;
 class client
iii {
iv public static void main(String…aa) throws Exception
v {
vi InetAddress inet= InetAddress.getLocalHost();
vii Socket so= new Socket(inet,5000);
 BufferedReader bw=
new BufferedReader(new
InputStreamReader(System.in));
 OutputStream
is1=so.getOutputStream();
viii PrintWriter bw1= new PrintWriter(is1,true);
 InputStream
is=so.getInputStream();
ix BufferedReader br= new BufferedReader(new
InputStreamReader(is));
 System.out.println(br.readL
ine());
x String str=bw.readLine();
xi bw1.println(str);
xii System.out.flush();
 }
 }
 
 Reply ↓ 

179 v.s. 
 July 22, 2012 at 3:43 pm
 
 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
 
 Reply ↓ 

A S. Nageswara Rao, Corporate Trainer Post author
 
 July 23, 2012 at
2:25 pm
 
 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).
 
 Reply ↓ 

180 Hacker 
 March 28, 2012 at 5:43 am
 
 This chat program(4Th
example) is unable to connect multiple clients. How to connect
multiple clients to a single server?
 
 Reply ↓ 

181 tom 
 March 1, 2012 at 5:58 pm
 
 i like the 4th example, would be
good if server allowed for multiple clients to talk to
server
 
 Reply ↓ 


You might also like