网络聊天室(NetChatRoom)2

·服务器端

 

ChatServerEvent

package chatserver;

import java.util.EventObject;

// 服务器事件
public class ChatServerEvent extends EventObject {
    String message;
    
    public ChatServerEvent(Object src, String message) {
        super(src);
        setMessage(message);
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

ChatServerImpl

package chatserver;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import chat.ChatServer;
import chat.Chatter;

// 服务器接口
public class ChatServerImpl extends java.rmi.server.UnicastRemoteObject implements ChatServer {
    static ChatServerImpl server = null;
    private final static String BINDNAME = "ChatServer";
    private final static String[] STATEMSG = new String[] { "服务器启动", "服务器停止" };
    List chatters = new ArrayList();
    List listeners = new ArrayList();
    
    protected ChatServerImpl() throws java.rmi.RemoteException {
        
    }
    
    public static ChatServerImpl getInstance() {
        try {
            if (server == null) {
                server = new ChatServerImpl();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            return null;
        }
        return server;
    }
    
    public void start() throws RemoteException, MalformedURLException {
        java.rmi.Naming.rebind(BINDNAME, server);
        notifyListener(STATEMSG[0]);
    }
    
    public void stop() throws RemoteException, NotBoundException, MalformedURLException {
        notifyListener(STATEMSG[1]);
        Iterator itr = chatters.iterator();
        while (itr.hasNext()) {
            UserInfo u = (UserInfo) itr.next();
            u.getChatter().serverStop();
        }
        java.rmi.Naming.unbind(BINDNAME);
    }
    
    public void addListener(ChatServerListener listener) {
        listeners.add(listener);
    }
    
    public void removeListense(ChatServerListener listener) {
        listeners.remove(listener);
    }
    
    void notifyListener(String msg) {
        Iterator itr = listeners.iterator();
        ChatServerEvent evt = new ChatServerEvent(this, msg);
        while (itr.hasNext()) {
            ((ChatServerListener) itr.next()).serverEvent(evt);
        }
    }
    
    public void login(String name, Chatter c) throws java.rmi.RemoteException {
        if (c != null && name != null) {
            UserInfo u = new UserInfo(name, c);
            notifyListener(u.getName() + " 进入聊天室");
            Iterator itr = chatters.iterator();
            while (itr.hasNext()) {
                UserInfo u2 = (UserInfo) itr.next();
                u2.getChatter().receiveEnter(name, c, false);
                c.receiveEnter(u2.getName(), u2.getChatter(), true);
            }
            chatters.add(u);
        }
    }
    
    public void logout(String name) throws java.rmi.RemoteException {
        if (name == null) {
            System.out.println("null name on logout: cannot remove chatter");
            return;
        }
        UserInfo u_gone = null;
        Iterator itr = null;
        
        synchronized (chatters) {
            for (int i = 0; i < chatters.size(); i++) {
                UserInfo u = (UserInfo) chatters.get(i);
                if (u.getName().equals(name)) {
                    notifyListener(name + " 离开聊天室");
                    u_gone = u;
                    chatters.remove(i);
                    itr = chatters.iterator();
                    break;
                }
            }
        }
        
        if (u_gone == null || itr == null) {
            System.out.println("no user by name of " + name + " found: not removing chatter");
            return;
        }
        
        while (itr.hasNext()) {
            UserInfo u = (UserInfo) itr.next();
            u.getChatter().receiveExit(name);
        }
    }
    
    public void chat(String name, String message) throws java.rmi.RemoteException {
        Iterator itr = chatters.iterator();
        
        while (itr.hasNext()) {
            UserInfo u = (UserInfo) itr.next();
            if (!name.equals(u.getName()))
                u.getChatter().receiveChat(name, message);
        }
        notifyListener(name + ":" + message);
    }
}

ChatServerListener

package chatserver;

import java.util.EventListener;

// 服务器监听接口
public interface ChatServerListener extends EventListener {
    public void serverEvent(ChatServerEvent evt);
}

Main

package chatserver;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.security.KeyStore;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;

// 服务器主函数
public class Main extends JFrame implements ChatServerListener {
    ChatServerImpl server = ChatServerImpl.getInstance();
    JTextArea textArea;
    JMenuBar menuBar;
    JToolBar toolBar;
    StarServerAction startAction = new StarServerAction();
    StopServerAction stopAction = new StopServerAction();
    
    public static void main(String[] args) {
        Main main = new Main();
        main.show();
    }
    
    public Main() {
        super("聊天-服务器");
        try {
            LocateRegistry.createRegistry(1099);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        setSize(300, 500);
        layoutComponents();
        String s1=this.getClass().getResource("").getPath();
        System.out.println(s1);
    }
    
    private void layoutComponents() {
        setupMenu();
        setupToolBar();
        textArea = new JTextArea();
        textArea.setSize(200, 300);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    
    private void setupMenu() {
        menuBar = new JMenuBar();
        JMenuItem startServer = new JMenuItem(startAction);
        JMenuItem stopServer = new JMenuItem(stopAction);
        JMenuItem exit = new JMenuItem("离开");
        exit.addActionListener(new AbstractAction() {
            
            @Override
            public void actionPerformed(ActionEvent evt) {
                exit();
            }
        });
        JMenu server = new JMenu("服务器");
        server.add(startServer);
        server.add(stopServer);
        server.add(exit);
        menuBar.add(server);
        setJMenuBar(menuBar);
    }
    
    private void setupToolBar() {
        toolBar = new JToolBar();
        JButton button = null;
        addTool(toolBar, startAction);
        addTool(toolBar, stopAction);
        
        getContentPane().add(toolBar, BorderLayout.NORTH);
    }
    
    JButton addTool(JToolBar toolBar, AbstractAction action) {
        JButton b = new JButton();
        b.setAction(action);
        b.setText(null);
        toolBar.add(b);
        return b;
    }
    
    private void exit() {
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
    
    public void serverEvent(ChatServerEvent evt) {
        textArea.append(evt.getMessage() + "\n");
    }
    
    class StarServerAction extends AbstractAction {
        public StarServerAction() {
            super("启动");
            putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../images/start.gif")));
            putValue(Action.SHORT_DESCRIPTION, "启动聊天服务器");
            putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control A"));
        }
        
        public void actionPerformed(ActionEvent evt) {
            try {
                server.addListener(Main.this);
                textArea.setText("");
                server.start();
                stopAction.setEnabled(true);
                this.setEnabled(false);
            } catch (Exception ex) {
                textArea.append("服务器启动错误\n");
                server.removeListense(Main.this);
                ex.printStackTrace();
                return;
            }
        }
    }
    
    class StopServerAction extends AbstractAction {
        public StopServerAction() {
            super("停止");
            putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../images/stop.gif")));
            putValue(Action.SHORT_DESCRIPTION, "停止聊天服务器");
            putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control O"));
            this.setEnabled(false);
        }
        
        public void actionPerformed(ActionEvent arg0) {
            try {
                server.stop();
                server.removeListense(Main.this);
                startAction.setEnabled(true);
                this.setEnabled(false);
            } catch (Exception e) {
                textArea.append("服务器停止错误\n");
                e.printStackTrace();
                return;
            }
        }
    }
}

 

UserInfo

package chatserver;

import chat.Chatter;

// 用户信息类
public class UserInfo {
    // 用户名
    private String name;
    // 远程客户端对象
    private Chatter chatter;
    
    public UserInfo(String name, Chatter chatter) {
        setName(name);
        setChatter(chatter);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Chatter getChatter() {
        return chatter;
    }

    public void setChatter(Chatter chatter) {
        this.chatter = chatter;
    }

}

 

posted @ 2021-07-09 16:20  他乡一故知  阅读(115)  评论(0编辑  收藏  举报