This chat application is developed using JDK 6 and Java RMI. This can be used for group-chat and one-to-one chat
To develop this application, we need following files.
- ChatServerInt.java - An interface for chat server.
- ChatClientInt.java - An interface for chat client.
- ChatServer.java - Implementation for chat server program.
- ChatClient.java - Implementation for chat client program.
- chatclient.policy - Policy to access the remote methods.
ChatServerInt.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatServerInt extends Remote {
void connect(String name, ChatClientInt c) throws RemoteException;
void disconnect(ChatClientInt c) throws RemoteException;
void broadcast(String name, String s) throws RemoteException;
void list(ChatClientInt c) throws RemoteException;
ChatClientInt lookup(String name) throws RemoteException;
}
ChatClientInt.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatClientInt extends Remote {
void update(String name, String s) throws RemoteException;
String getName() throws RemoteException;
}
ChatServer.java
import java.io.PrintStream; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List;
public class ChatServer implements ChatServerInt {
private static final long serialVersionUID = 1L;
private List myclients;
private List clientNames;
private static final String name = "server";
public ChatServer() throws RemoteException {
myclients = new ArrayList();
clientNames = new ArrayList();
}
public synchronized void disconnect(ChatClientInt c) throws RemoteException {
myclients.remove(c);
clientNames.remove(c.getName());
writeLog(c.getName() + " disconnected at {0}");
for(ChatClientInt client: myclients) {
client.update(name, c.getName() + " has left.");
}
}
public synchronized void list(ChatClientInt c) throws RemoteException {
c.update(name, "Active users: " + clientNames.toString());
}
public synchronized ChatClientInt lookup(String name) throws RemoteException {
ChatClientInt c = null;
int index = clientNames.indexOf(name);
if (-1 != index) {
c = myclients.get(index);
}
return c;
}
public synchronized void connect(String n, ChatClientInt c) throws RemoteException {
for(ChatClientInt client: myclients) {
client.update(name, n + " is joining now...");
}
clientNames.add(n);
myclients.add(c);
int count = myclients.size();
StringBuffer wcmMsg = new StringBuffer("Welcome ").append(n).append(", ");
wcmMsg.append("There ").append((1 == count)? "is " : "are ").append(
count).append((1 == count)? " user: " : " users: ");
wcmMsg.append(clientNames.toString());
c.update(name, wcmMsg.toString());
writeLog(n + " connected at {0}");
}
public synchronized void broadcast(String name, String s) throws RemoteException {
for(ChatClientInt client: myclients) {
client.update(name, s);
}
writeLog("{0}: " + name + ": " + s);
}
public static void main (String[] args) {
if (1 != args.length) {
System.out.println("Usage: java ChatServer <server_port>");
System.out.println("Example: java ChatServer 2001");
return;
}
int port = Integer.parseInt(args[0]);
try {
System.setOut(new PrintStream("server.log"));
ChatServer server = new ChatServer();
LocateRegistry.getRegistry(port).bind("ChatServer",
UnicastRemoteObject.exportObject(server, 0));
writeLog("Server started at {0}, waiting for connections...");
} catch(Exception e) {
e.printStackTrace();
}
}
private static void writeLog(String log) {
System.out.println(MessageFormat.format(log, new Date().toString()));
}
}
ChatClient.java
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
public class ChatClient extends UnicastRemoteObject implements ChatClientInt, Runnable {
private static final long serialVersionUID = 1L;
private ChatServerInt server;
private String name;
private ChatClientInt friend;
private static final String LIST = "LIST";
private static final String QUIT = "QUIT";
private static final String HELLO = "Hello ";
public ChatClient(ChatServerInt cs, String name) throws RemoteException {
this.name = name;
this.server = cs;
server.connect(name, this);
}
public synchronized void update(String name, String s) throws RemoteException {
if (! this.name.equals(name)) {
System.out.println(name + ": " + s);
}
}
public void run() {
Scanner in=new Scanner(System.in);
String msg;
while(true) {
try {
msg=in.nextLine();
msg = msg.trim();
if (QUIT.equals(msg)) {
server.disconnect(this);
in.close();
System.exit(0);
} else if (LIST.equals(msg)){
server.list(this);
} else if (msg.startsWith(HELLO) && msg.contains(",")) {
String s[] = msg.substring(0, msg.indexOf(",")).split(" ");
String user = s[s.length-1].trim();
friend = server.lookup(user);
if (null != friend) {
friend.update(name, msg);
} else {
server.broadcast(name, msg);
}
} else if (! "".equals(msg)) {
server.broadcast(name, msg);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (3 != args.length) {
System.out.println("Usage: java ChatClient <server_ip> <server_port> <user_name>");
System.out.println("Example: java ChatClient 127.0.0.1 2001 user1");
return;
}
String host = args[0];
int port = Integer.parseInt(args[1]);
String name = args[2];
try {
Registry registry = LocateRegistry.getRegistry(host, port);
ChatServerInt server = (ChatServerInt) registry.lookup("ChatServer");
Thread t = new Thread(new ChatClient(server, name));
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getName() {
return name;
}
}
chatclient.policy
Compile the source and put the classes into bin.
javac -d ../bin/ *.java
Now run rmiregstry (better to use a port) in a new console and leave it as it is.
rmiregistry 2001
Start the chat server program with the same port number 2001.
java -Djava.security.policy= -Djava.rmi.server.codebase=file:/ ChatServer 2001
Now start as many clients you want...
In case you want run the client from the same machine where chat server is running, use following...
java ChatClient 127.0.0.1 2001 user1
In case of remote machine, you must give the server ip in command-line...
java ChatClient 2001 user2
Key Features
grant {
permission java.security.AllPermission;
};
Compile the source and put the classes into bin.
javac -d ../bin/ *.java
Now run rmiregstry (better to use a port) in a new console and leave it as it is.
rmiregistry 2001
Start the chat server program with the same port number 2001.
java -Djava.security.policy=
Now start as many clients you want...
In case you want run the client from the same machine where chat server is running, use following...
java ChatClient 127.0.0.1 2001 user1
In case of remote machine, you must give the server ip in command-line...
java ChatClient
Key Features
- When user1 comes in all other available users will get a notification saying "user1 is joining now...".
- The new user will get a wecome message from server and will get to know how many available users are there and who are they.
- When a user types some message and press enter, the message will be sent to all the users (except the current user) via server.
- If user1 wants to chat with a specific user(say user2), he can type "Hello user2, blah blah..." and only user2 will get that message from user1.
- A user can type "LIST" to know the list of current users.
- A user can type "QUIT" in case he wants to leave chat.
- All the group-chat conversations and user connect/disconnect are logged into a log file at server side.
when i am compiling the code....i get an error in the line.. "c=myclients.get(index)"...it says :"incompatible types".....i dont know how to solve that....please help..!!!!
ReplyDeleteHi Aradhna,
DeleteNice to know that you are following this. Yes there was an issue in ChatServer. the ArrayList used was the generic one. I have updated ChatServer.java code. Now I am using parameterized ArrayList. Please take the latest and try.
Please revert me back if its fine/still having issues whatever.
btw, which version of jdk do you use?
Hello Gourahari das!
Deletei have worked on the above code but still the same error as mention Aradhna Karva.... Please suggest.....
hi aradhana,
ReplyDeletecall me if you want answer......
Give the URL where i can get the updated program using parameterized ArrayList...
ReplyDeleteCASINO ONLINE NOW LIVE | NJMPR - JTA Hub
ReplyDeleteNEW JAM. — 전주 출장안마 Casino-on-line casino players in NJ 의정부 출장안마 have access 상주 출장마사지 to a 동두천 출장안마 new range of options for betting, including a live casino section with 충주 출장샵 a