📄 chatroomserver.java
字号:
/* * ChatRoomServer.java * * Created on 2008年4月2日, 下午7:33 *//** * * @author Owner */import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;public class ChatRoomServer extends javax.swing.JFrame implements Runnable { ServerSocket serverSock; public final static int DEFAULT_PORT=6666;//默认端口号 Thread chatAcceptThread;//启动接受连接的线程 BroadcastThread broadcastThread;//广播thread; run when server is listening java.util.Vector clients;//记录连接的线程 java.util.Vector clientsInfor;//记录连接线程的信息 public static int index=0; /** Creates new form ChatRoomServer */ public ChatRoomServer() { try{ initComponents(); }catch(Exception e){ e.printStackTrace(); } serverListen();//服务器开始监听 } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jButton1.setText("退出"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(138, 138, 138) .add(jButton1) .addContainerGap(205, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jButton1) ); getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformedexit(); // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated this.addWindowListener(new ChatFrame_WindowAdapter(this)); // TODO add your handling code here: }//GEN-LAST:event_formWindowActivated public void processMsg(String str){// jTextArea1.append(str); } private void serverListen(){ try{ serverSock=new ServerSocket(DEFAULT_PORT); }catch(IOException e){ processMsg(e.toString()); processMsg("server failed!\n"); } processMsg("server listening on port:"+DEFAULT_PORT); clients=new java.util.Vector(); //记录连接的线程 clientsInfor=new java.util.Vector();//记录连接线程的信息 chatAcceptThread=new Thread(this);//启动接受连接的线程 chatAcceptThread.start(); broadcastThread=new BroadcastThread(this);//广播线程 //broadcastThread.start(); } public void run(){//接受连接并记录线程信息 int i=0; try{ while(true){ Socket clientSock=serverSock.accept(); CommunicateThread ct=new CommunicateThread(clientSock,this,index);//创建线程保持连接 public static int index=0; clients.add(ct);//record Communicate Thread; i++; index++;//version2 clientsInfor.add("Thread-"+i); processMsg("Thread-"+i+"join in\n"); } }catch(IOException e){ processMsg(e.toString()); } } public void exit(){ broadcastThread.broadcast("Server exit!"); try{ serverSock.close(); }catch(IOException ioe){} finally{ System.exit(0); } } //还有一个回收无用连接thread 的线程 /** * @param args the command line arguments */ public static void main(String args[]) { ChatRoomServer chat=new ChatRoomServer(); chat.show(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }class CommunicateThread extends Thread{//保持连接线程 protected Socket clientSock; protected BufferedReader in=null; protected PrintWriter out; ChatRoomServer chatFrame; boolean isTrue=true;//run() java.util.Vector inforStack; int index2;// public CommunicateThread(Socket Sock,ChatRoomServer cFrame,int index){ clientSock=Sock; chatFrame=cFrame; index2=index; inforStack=new java.util.Vector(); try{ in=new BufferedReader(new InputStreamReader(clientSock.getInputStream())); out=new PrintWriter(clientSock.getOutputStream()); }catch(IOException ei){ try{ clientSock.close(); }catch(IOException ei2){ } chatFrame.processMsg(ei.toString()); return; } this.start(); } public void run(){ String infor; //用于往信息栈些信息 try{ while(isTrue){ infor=in.readLine(); if(infor.equals("Client exit!")){ writeInformation(infor);//把信息写到信息栈,以倍广播出去 stopRun(); }else if(infor!=null){ writeInformation(infor); }//else break; try{ Thread.sleep(100);//version2 }catch(InterruptedException ex){} } }catch(IOException e){ ;} finally{ try{ in.close(); out.close(); clientSock.close(); chatFrame.clients.remove(index2);//在clients中清除本线程序 ChatRoomServer.index--;// }catch(IOException ei){;} } } public void writeInformation(String infor){//写信息栈 inforStack.add(infor); } private void stopRun(){//终止线程 isTrue=false; } public void sendInformation(String str){//发送信息 try{ out.println(str); out.flush(); }catch(Exception e){;} } }class BroadcastThread extends Thread{//广播线程 ChatRoomServer chatFrame2; java.util.Vector chatClients;//连接线程信息 java.util.Vector msgStack;//信息栈 java.util.Vector clientMsg;//记录客户发送的信息 CommunicateThread comThread1;//用于 CommunicateThread comThread2; String string;//information in inforStack String clientName;//client thread name String broadcastInfor;//broadcast information=clientName+string; public BroadcastThread(ChatRoomServer cFrame){ chatFrame2=cFrame; chatClients=chatFrame2.clients; //纪录的线程 clientMsg=chatFrame2.clientsInfor; this.start(); } public void broadcast(String str){//广播 for(int k=0;k<chatClients.size();k++){//send to everyone分别调用每个连接线程,发送信息 comThread2=(CommunicateThread)chatClients.get(k); comThread2.sendInformation(str); } } public void run(){ try{ while(true){ for(int i=0;i<chatClients.size();i++){ comThread1=(CommunicateThread)chatClients.get(i); msgStack=comThread1.inforStack;//得到每个连接的信息栈 clientName=(String)clientMsg.get(i);//客户名 //读取每个连接线程的信息栈并把信息发送出去 for(int j=0;j<msgStack.size();j++){ string=(String)msgStack.get(j); //注意分号string 表示这个进程的信息 broadcastInfor=clientName+"->"+string; broadcast(broadcastInfor); } //clear the inforStack msgStack.removeAllElements();//清除以发送的信息 } try{ Thread.sleep(100);//version2 }catch(InterruptedException ex){} } }catch(Exception e){} } }//处理窗口关闭事件的适配器class ChatFrame_WindowAdapter extends java.awt.event.WindowAdapter{ ChatRoomServer chatFrame; public ChatFrame_WindowAdapter(ChatRoomServer chatFrame){ this.chatFrame=chatFrame; } public void windowClosing(WindowEvent e){//exit program chatFrame.exit();//reference to the method exit() in ChatRoomServer. }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -