-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
96 lines (82 loc) · 2.49 KB
/
Copy pathChatServer.java
File metadata and controls
96 lines (82 loc) · 2.49 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.StringTokenizer;
import java.util.Vector;
public class ChatServer {
private static Vector clientSockets;
private static Vector loginNames;
ChatServer() throws IOException{
ServerSocket server = new ServerSocket(5217);
clientSockets = new Vector();
loginNames = new Vector();
while(true){
Socket client = server.accept();
AcceptClient acptclient = new AcceptClient(client);
}
}
public static void main(String args[]) throws IOException{
ChatServer cs = new ChatServer();
}
class AcceptClient extends Thread{
Socket clientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket client) throws IOException{
clientSocket = client;
din = new DataInputStream(client.getInputStream());
dout = new DataOutputStream(client.getOutputStream());
String loginName = din.readUTF();
loginNames.add(loginName);
clientSockets.add(clientSocket);
start();
}
public void run(){
while(true){
try {
String msgFromClient = din.readUTF();
StringTokenizer st = new StringTokenizer(msgFromClient);
String logName = st.nextToken();
String msgType = st.nextToken();
int io =-1;
String msg = "";
while(st.hasMoreTokens()){
msg = msg+" "+st.nextToken();
}
if(msgType.equals("LOGIN")){
for(int i=0;i<loginNames.size();i++){
Socket pSocket = (Socket) clientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(logName+" has logged in.");
}
}
else if(msgType.equals("LOGOUT")){
for(int i=0;i<loginNames.size();i++){
if(logName.equals(loginNames.elementAt(i)))
io=i;
Socket pSocket = (Socket) clientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(logName+" has logged out.");
if(io>=0){
loginNames.removeElementAt(io);
clientSockets.removeElementAt(io);
}
}
}
else{
for(int i=0;i<loginNames.size();i++){
Socket pSocket = (Socket) clientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(logName+": "+msg);
}
}
if(msgType.equals("LOGOUT"))
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}