⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatclient.java

📁 使用RMI实现的聊天室
💻 JAVA
字号:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;

public class ChatClient extends UnicastRemoteObject implements IChatClient {

	ChatFrame gui;

	String name;

	IChatServer server;

	String serverUrl;

	protected ChatClient(final String name, String url) throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
		this.name = name;
		this.serverUrl = url;
		gui = new ChatFrame("Chat with RMI");
		gui.input.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try {
					server.send(new Packet(name, gui.input.getText().trim()));
					gui.input.setText("");
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
		gui.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				disconnect();
				System.exit(0);
			}
		});

		this.connect();
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void receiveEnter(String name) throws RemoteException {
		// TODO Auto-generated method stub
		gui.output.append(name + " entered @" + new Date() + "\n");
	}

	public void receiveExit(String name) throws RemoteException {
		// TODO Auto-generated method stub
		gui.output.append(name + "left @" + new Date() + "\n");
	}

	public void receiveMessage(Packet message) throws RemoteException {
		// TODO Auto-generated method stub
		gui.output.append(message.getName() + ":" + message.getText() + "\n");
	}

	private void connect() {
		try {
			server = (IChatServer) Naming.lookup("//localhost:8808/RMI");
			System.out.println((server == null) + name);
			server.login(name, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void disconnect() {
		try {
			server.logout(name);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			new ChatClient("cong", "//200.200.200.20:8808");
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -