-
Notifications
You must be signed in to change notification settings - Fork 0
/
RMIChatServer.java
125 lines (121 loc) · 2.32 KB
/
RMIChatServer.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package chat;
import java.rmi.*;
import java.rmi.registry.* ;
import java.rmi.server.*;
import java.util.*;
public class RMIChatServer extends UnicastRemoteObject implements ChatServerInterface
{
String id = "Bhavesh";
Vector<ClientInfo> v;
public RMIChatServer() throws RemoteException
{
v = new Vector<ClientInfo>();
try
{
LocateRegistry.createRegistry(1099);
Naming.rebind(id,this);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void login(String name,ChatClientInterface ref)
{
ClientInfo ci = new ClientInfo(name,ref);
v.add(ci);
broadcastMsg(name + " joined the chat");
broadcastList();
}
public void takeMsg(String msg)
{
broadcastMsg(msg);
}
class ClientInfo
{
String name;
ChatClientInterface ref;
public ClientInfo(String name,ChatClientInterface ref)
{
this.name = name;
this.ref = ref;
}
public boolean equals(Object o)
{
if(o instanceof ClientInfo)
{
return (((ClientInfo)o).name.equals(name));
}
else
{
return false;
}
}
}
public void logout(String name)
{
v.remove(new ClientInfo(name,null));
broadcastMsg(name + " has left the chat");
broadcastList();
}
public void broadcastMsg(String msg)
{
Enumeration<ClientInfo> en = v.elements();
while(en.hasMoreElements())
{
ClientInfo ci = en.nextElement();
try
{
ci.ref.takeMsg(msg);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void broadcastList()
{
Vector<String> v2 = new Vector<String>();
Enumeration<ClientInfo> en = v.elements();
while(en.hasMoreElements())
{
ClientInfo ci = en.nextElement();
v2.add(ci.name);
}
Enumeration<ClientInfo> en1 = v.elements();
while(en1.hasMoreElements())
{
ClientInfo ci = en1.nextElement();
try
{
ci.ref.takeClientList(v2);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public ChatClientInterface giveRef(String hisName)
{
ClientInfo ci = new ClientInfo(hisName,null);
if(v.contains(ci))
{
int index = v.indexOf(ci);
ci = v.get(index);
}
return ci.ref;
}
public static void main(String[] args)
{
try
{
new RMIChatServer();
}
catch(Exception e)
{
System.out.println(e);
}
}
};