java五子棋代码分析 java五子棋的简单思路( 四 )


statusBar.setText("");
// 初始化菜单
JMenu fileMenu = new JMenu();
fileMenu.setText("文件");
JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.setText("退出");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitActionPerformed(e);
}
});
fileMenu.add(exitMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
// 将组件进行布局
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane(connectInfoList);
pane.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "客户端连接信息"));
jPanel1.add(new JScrollPane(pane), BorderLayout.CENTER);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(statusBar, BorderLayout.SOUTH);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
this.pack();
}
/**
* 退出菜单项事件
* @param e
*/
public void exitActionPerformed(ActionEvent e){
// 向客户端发送断开连接信息
sendMsgToClients(new StringBuffer(Constants.QUIT_IDENTIFER));
// 关闭所有的连接
closeAll();
System.exit(0);
}
/**
* 处理窗口关闭事件
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
exitActionPerformed(null);
}
}
/**
* 刷新聊天室,不断刷新clientProcessors,制造最新的用户列表
*/
public static void notifyRoomPeople(){
StringBuffer people = new StringBuffer(Constants.PEOPLE_IDENTIFER);
for (int i = 0; iclientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
people.append(Constants.SEPERATOR).append(c.clientName);
}
// 用sendClients方法向客户端发送用户列表的信息
sendMsgToClients(people);
}
/**
* 向所有客户端群发消息
* @param msg
*/
public static synchronized void sendMsgToClients(StringBuffer msg) {
for (int i = 0; iclientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
System.out.println("send msg: " + msg);
c.send(msg);
}
}
/**
* 关闭所有连接
*/
public static void closeAll(){
while (clientProcessors.size()0) {
ClientProcessor c = (ClientProcessor) clientProcessors.firstElement();
try {
// 关闭socket连接和处理线程
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}
/**
* 判断客户端是否合法 。
* 不允许同一客户端重复登陆,所谓同一客户端是指IP和名字都相同 。
* @param newclient
* @return
*/
public static boolean checkClient(ClientProcessor newclient){
if (clientProcessors.contains(newclient)){
return false;
} else {
return true;
}
}
/**
* 断开某个连接 , 并且从连接列表中删除
* @param client
*/
public static void disconnect(ClientProcessor client){
disconnect(client, true);
}
/**
* 断开某个连接,根据要求决定是否从连接列表中删除
* @param client
* @param toRemoveFromList
*/
public static synchronized void disconnect(ClientProcessor client, boolean toRemoveFromList){
try {
//在服务器端程序的list框中显示断开信息
connectInfoList.add(client.clientIP + "断开连接");

推荐阅读