-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatClient.java
92 lines (91 loc) · 1.54 KB
/
ChatClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.*;
import java.net.*;
class ChatClient
{
static String user;
public static void main(String s[])
{
try
{
System.out.println("client started");
Socket sk=new Socket("192.168.0.2",1500);
System.out.println("connection established");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the username.");
user=br.readLine();
DataOutputStream dout=new DataOutputStream(sk.getOutputStream());
DataInputStream din=new DataInputStream(sk.getInputStream());
dout.writeUTF("login#"+user);
dout.flush();
String verify=din.readUTF();
if("correct".equals(verify))
{
System.out.println("Welcome "+user);
new ReaderThread(din);
startChat(dout);
}
else
{
System.out.println("This user already connected,reconnect with the different username");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
static void startChat(DataOutputStream dout)
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Start to enter the message,Enter the 'Stop' to terminate");
while(true)
{
String msg=br.readLine();
if(msg.equals("stop"))
{
msg=user+":"+msg;
dout.writeUTF("logout#"+msg);
dout.flush();
break;
}
else
{
msg=user+":"+msg;
dout.writeUTF("message#"+msg);
dout.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class ReaderThread extends Thread
{
DataInputStream din;
ReaderThread(DataInputStream din)
{
this.din=din;
setDaemon(true);
start();
}
public void run()
{
try
{
while(true)
{
String msg=din.readUTF();
System.out.println(msg);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}