-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChatServer.java
More file actions
99 lines (92 loc) · 2.75 KB
/
Copy pathChatServer.java
File metadata and controls
99 lines (92 loc) · 2.75 KB
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
92
93
94
95
96
97
98
99
import java.util.ArrayList;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.io.BufferedInputStream;
class ServerHandler implements Runnable
{
public static ArrayList<Socket> socketList=new ArrayList<Socket>();
public static ArrayList<ServerHandler> threadList=new ArrayList<ServerHandler>();
static int count=1;
Socket s = null;
Thread thread=null;
DataInputStream dis=null;
DataOutputStream dos=null;
public ServerHandler(Socket s)
{
this.s = s;
thread = new Thread(this,"Client"+count++);
try{
dis=new DataInputStream(new BufferedInputStream(s.getInputStream()));
dos=new DataOutputStream(s.getOutputStream());}
catch(IOException io){}
socketList.add(s);
threadList.add(this);
thread.start();
}
public void run()
{
try
{
String msg="";
while(!msg.equals("exit"))
{
msg=dis.readUTF();
//byte []bmsg = dis.read();
// msg=new String(bmsg);
if(!msg.equals("exit"))
{for(int i=0;i<socketList.size();i++)
{
try{if(threadList.get(i)!=this) {threadList.get(i).dos.writeUTF(msg);} }catch(IOException io){}
}}
else
this.dos.writeUTF("");
}
int tempcnt=0;
for(Socket temp : socketList)
{
if(temp==this.s)
{
socketList.remove(temp);
threadList.remove(tempcnt);
tempcnt=0;
break;
}
tempcnt++;
}
s.close();
//dis.close();
//dos.close();
}
catch(IOException io){System.out.print(io);}
}
}
public class ChatServer
{
public static void main(String []args) throws IOException
{
ServerSocket server = new ServerSocket(5000);
System.out.println("Server Started...");
// SocketAddress SocketAddress = null;
Socket socket=null;
while(true)
{
try
{
System.out.println("Waiting for Client...");
socket = server.accept();
System.out.println("New Client Connected...");
new ServerHandler(socket);
}
catch(UnknownHostException uh)
{
System.out.println(uh);
}
}
}
}