-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatServer.java
86 lines (86 loc) · 1.31 KB
/
ChatServer.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
import java.io.*;
import java.net.*;
class ChatServer
{
static int count;
static Socket sk[]=new Socket[2];
public static void main(String s[])
{
try
{
ServerSocket ss=new ServerSocket(1500);
String users[]=new String[2];
count=0;
System.out.println("Waiting for client request...");
Socket sk1=ss.accept();
sk[0]=sk1;
new ClientThread(sk1,users);
System.out.println("waiting for client request...");
Socket sk2=ss.accept();
sk[1]=sk2;
new ClientThread(sk2,users);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class ClientThread extends Thread
{
String users[];
Socket sk;
ClientThread(Socket sk,String users[])
{
this.users=users;
this.sk=sk;
start();
}
public void run()
{
try
{
DataInputStream din=new DataInputStream(sk.getInputStream());
DataOutputStream dout=new DataOutputStream(sk.getOutputStream());
String usr=din.readUTF();
if(ChatServer.count==1)
{
if(users[0].equals(usr))
{
dout.writeUTF("incorrect");
dout.flush();
return;
}
else
{
dout.writeUTF("correct");
dout.flush();
}
}
else
{
users[0]=usr;
ChatServer.count++;
dout.writeUTF("correct");
dout.flush();
}
while(true)
{
String str=din.readUTF();
for(int i=0;i<=1;i++)
{
DataOutputStream dout2=new DataOutputStream(ChatServer.sk[i].getOutputStream());
if(ChatServer.sk[i]!=sk)
{
dout2.writeUTF(str);
dout2.flush();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}