利用RMI技术开发聊天案例(尚有疑问,待解决!!!)

接口文件:IChatClient.java

package com.cjq.rmi.inter;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IChatClient extends Remote {
	//获取客户名
	public String getName() throws RemoteException;
	//广播新加入聊天者
	public void sendMessage(String msg) throws RemoteException;
}

接口文件:IChatService.java:

package com.cjq.rmi.inter;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IChatService extends Remote {
	//登录客户加入聊天室
	public void addClient(IChatClient c,String msg) throws RemoteException;
	//向所有已进入的聊天者广播退出者
	public void removeClient(IChatClient c,String msg) throws RemoteException;
	//将消息发送给所有当前的用户
	public void sendMessage(IChatClient c,String msg) throws RemoteException;
}

服务 类:ChatService.java

package com.cjq.rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

import com.cjq.rmi.inter.IChatClient;
import com.cjq.rmi.inter.IChatService;

public class ChatService extends UnicastRemoteObject implements IChatService {
	Vector<IChatClient> clients;
	
	public ChatService() throws RemoteException{
		super();
		clients = new Vector<IChatClient>();
	}

	@Override
	public void addClient(IChatClient c, String msg) throws RemoteException {
		System.out.println("Add Client entry.....");
		if(!clients.contains(c)){//此处if条件永真,为何??
			for(int i=0;i<clients.size();i++){
				sendMessage(clients.elementAt(i),msg);
			}
//			clients.addElement(c);
			clients.add(c);
			System.out.println("Add Client end.....");
		}
	}

	@Override
	public void removeClient(IChatClient c, String msg) throws RemoteException {
		System.out.println("Remove Client entry.....");
		if(clients.contains(c)){//此处为何c不属于clients??
			for(int i =0;i<clients.size();i++){
				sendMessage((IChatClient)clients.elementAt(i),msg);
			}
			clients.remove(c);
			System.out.println("Remove Client end.....");
		}
	}

	@Override
	public void sendMessage(IChatClient c, String msg) throws RemoteException {

		if(!clients.contains(c)){
			return;
		}
		for(int i =0;i<clients.size();i++){
			String user = c.getName();
			if(user==null || user.equals("")){
				user = "anonymous";
			}
			(clients.elementAt(i)).sendMessage(user+":"+msg);
			System.out.println(user+":"+msg);
		}
	}

}



ChatServer.java :

package com.cjq.rmi;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class ChatServer {

	public static void main(String[] args) throws RemoteException {

//		System.setSecurityManager(new RMISecurityManager());
		LocateRegistry.createRegistry(1099);
		try{
			ChatService service = new ChatService();
			Naming.rebind("rmi://localhost/IChatService",service);
			System.out.println("Service Started");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}


ChatClient.java : 

package com.cjq.rmi;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import com.cjq.rmi.inter.IChatClient;
import com.cjq.rmi.inter.IChatService;

public class ChatClient extends Frame implements IChatClient, ActionListener {
	
	IChatService service = null;
	TextField servername,serverport,username;
	Button connect,disconnect;
	TextField message;
	Button send;
	TextArea fromserver;
	boolean connected = false;
	String title,user="";
	public ChatClient(){
		
	}
	public ChatClient(String str) {
		super(str);
		
//		System.setSecurityManager(new RMISecurityManager());
		try {
			LocateRegistry.getRegistry(1099);
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		
		setBounds(50,20,400,400);
		setLayout(new FlowLayout(FlowLayout.CENTER,25,10));
		title = str;
		setStatus();
		add(new Label("Chat Server Name:"));
		servername = new TextField(20);
		servername.setEnabled(false);
		add(servername);
		servername.setText("localhost");;
		add(new Label("Chat Server Port:"));
		serverport = new TextField(20);
		serverport.setEnabled(false);
		add(serverport);
		serverport.setText("1099");
		
		add(new Label("Your User Name :"));
		username = new TextField(20);
		add(username);
		username.setText("");
		
		connect = new Button("Connect");
		connect.addActionListener(this);
		add(connect);
		
		disconnect = new Button("Disconnect");
		disconnect.addActionListener(this);
		add(disconnect);
		
		message = new TextField(30);
		add(message);
		
		send = new Button("Send");
		send.addActionListener(this);
		add(send);
		
		fromserver  = new TextArea(10,50);
		add(fromserver);
		fromserver.setEditable(false);
		
//		try{
//			UnicastRemoteObject.exportObject(this);
//		}catch(RemoteException e){
//			e.printStackTrace();
//		}
		setVisible(true);
		this.setLocationRelativeTo(null);
	}
	
	private void connect(){
		try{
			service = (IChatService)Naming.lookup("rmi://localhost/IChatService");
			connected = true;
			setStatus();
			user = username.getText().trim();
			service.addClient(this, user+"连入");//this1...
		}catch(Exception e){
			fromserver.append("Err Connecting ...\n");
			connected = false;
			setStatus();
			service = null;
			e.printStackTrace();
		}
	}
	
	private void disconnect(){
		try{
			if(service ==null){
				return;
			}
			service.removeClient(this, user+"退出");//this2. 实际this1不等于this2。
			//因此导致无法remove Client,具体如何remove,待解决 //TODO
			service = null;
		}catch(Exception e){
			fromserver.append("Error Disconnecting ...\n");
		}finally{
			connected = false;
			setStatus();
		}
	}
	
	private void setStatus(){
		if(connected){
			setTitle(title+": Connected");
		}else{
			setTitle(title+": Not connected");
		}
	}
	
	public String getName(){
		return user;
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {

		if(e.getSource()==connect){
			connect();
			if(connected){
				username.setEnabled(true);
				connect.setEnabled(false);
			}
		}else if(e.getSource()==disconnect){
			disconnect();
			servername.setEnabled(true);
			serverport.setEnabled(true);
			username.setEnabled(true);
			connect.setEnabled(true);
		}else if(e.getSource()==send){
			if(service==null){
				return;
			}
			try{
				service.sendMessage(this, message.getText());
//				fromserver.append(getName()+":"+message.getText()+"\n");
				message.setText("");
			}catch(RemoteException ee){
				ee.printStackTrace();
				fromserver.append("Error Sending Message...\n");
			}
		}
	}

	@Override
	public void sendMessage(String msg) throws RemoteException {

		fromserver.append(msg+"\n");
		System.out.println(msg);
	}

	public static void main(String[] args) {
		ChatClient client = new ChatClient("Chat Client");
	}

}




你可能感兴趣的:(利用RMI技术开发聊天案例(尚有疑问,待解决!!!))