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

📄 frame1.java~1~

📁 基于java开发的类似QQ的聊天工具的源程序
💻 JAVA~1~
字号:
package chatserver;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
import java.net.*;//需要增加的包
import java.io.*;
import java.util.Vector;
import java.util.StringTokenizer;
/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class Frame1 extends JFrame {
  JPanel contentPane;
  JPanel jPanel1 = new JPanel();
  JPanel jPanel2 = new JPanel();
  XYLayout xYLayout1 = new XYLayout();
  BorderLayout borderLayout1 = new BorderLayout();
  BorderLayout borderLayout2 = new BorderLayout();
  JPanel jPanel3 = new JPanel();
  JLabel jLabel1 = new JLabel();
  JLabel jLabel2 = new JLabel();
  JLabel jLabel3 = new JLabel();
  PaneLayout paneLayout1 = new PaneLayout();
  JPanel jPanel4 = new JPanel();
  JLabel jLabel4 = new JLabel();
  JLabel jLabel5 = new JLabel();
  JLabel jLabel6 = new JLabel();
  PaneLayout paneLayout2 = new PaneLayout();
  JScrollPane jScrollPane1 = new JScrollPane();
  JScrollPane jScrollPane2 = new JScrollPane();
  JTextArea jTextArea2 = new JTextArea();
  JPanel jPanel5 = new JPanel();
  JTextField jTextField1 = new JTextField();
  PaneLayout paneLayout3 = new PaneLayout();
  JButton send = new JButton();
  JButton sysexit = new JButton();
  JTextField jTextField2 = new JTextField();

//定义相关变量
  ServerSocket serverSocket=null;//建立服务器的socket
  Socket socket=null;  //用来存储一个连接套接字
  BufferedReader cin=null;//用来实现接受从客户端发来的数据流
  PrintWriter cout=null;//用来实现向客户端发送信息的流
  static Vector clients=new Vector(20);   //用vector向量数组存储连接客户变量
  static int active_connects=0;//记录目前连接的客户数
  java.awt.List list1 = new java.awt.List();
  JButton link = new JButton();//用来列出目前连接的客户数


  //Construct the frame
  public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
      run();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  //Component initialization
  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(xYLayout1);
    this.setLocale(java.util.Locale.getDefault());
    this.setSize(new Dimension(407, 379));
    this.setTitle("网络聊天服务器");
    jPanel1.setLayout(borderLayout1);
    jPanel2.setLayout(borderLayout2);
    jLabel1.setBorder(BorderFactory.createEtchedBorder());
    jLabel1.setText("用户名");
    jLabel2.setBorder(BorderFactory.createEtchedBorder());
    jLabel2.setText("IP地址");
    jLabel3.setBorder(BorderFactory.createEtchedBorder());
    jLabel3.setToolTipText("");
    jLabel3.setText("连接情况");
    jPanel3.setLayout(paneLayout1);
    jLabel4.setBorder(BorderFactory.createEtchedBorder());
    jLabel4.setText("信息类型");
    jLabel5.setBorder(BorderFactory.createEtchedBorder());
    jLabel5.setText("信息来源");
    jLabel6.setBorder(BorderFactory.createEtchedBorder());
    jLabel6.setText("信息内容");
    jPanel4.setLayout(paneLayout2);
    jTextField1.setEditable(false);
    jTextField1.setText("");
    jPanel5.setLayout(paneLayout3);
    send.setText("发送");
    send.addActionListener(new Frame1_send_actionAdapter(this));
    sysexit.setText("退出");
    sysexit.addActionListener(new Frame1_sysexit_actionAdapter(this));
    jTextArea2.setText("");
    link.setText("连接");
    link.addActionListener(new Frame1_link_actionAdapter(this));
    contentPane.add(jPanel1,    new XYConstraints(-2, 0, 402, 152));
    jPanel1.add(jPanel3, BorderLayout.NORTH);
    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(list1, null);
    contentPane.add(jPanel2,     new XYConstraints(-1, 160, 401, 140));
    jPanel2.add(jPanel4,  BorderLayout.NORTH);
    jPanel4.add(jLabel4,         new PaneConstraints("jLabel4", "jLabel4", PaneConstraints.ROOT, 0.5f));
    jPanel4.add(jLabel5,         new PaneConstraints("jLabel5", "jLabel4", PaneConstraints.RIGHT, 0.7431421f));
    jPanel4.add(jLabel6,         new PaneConstraints("jLabel6", "jLabel5", PaneConstraints.RIGHT, 0.63758385f));
    jPanel2.add(jScrollPane2, BorderLayout.CENTER);
    jPanel2.add(jPanel5, BorderLayout.SOUTH);
    contentPane.add(jTextField2, new XYConstraints(1, 295, 306, 31));
    contentPane.add(jTextField1,  new XYConstraints(2, 329, 242, -1));
    contentPane.add(send,  new XYConstraints(328, 301, 60, 22));
    contentPane.add(sysexit,   new XYConstraints(329, 329, 60, 22));
    contentPane.add(link, new XYConstraints(261, 330, 56, 22));
    jScrollPane2.getViewport().add(jTextArea2, null);
    jPanel3.add(jLabel1,      new PaneConstraints("jLabel1", "jLabel1", PaneConstraints.ROOT, 0.5f));
    jPanel3.add(jLabel2,      new PaneConstraints("jLabel2", "jLabel1", PaneConstraints.RIGHT, 0.75124377f));
    jPanel3.add(jLabel3,      new PaneConstraints("jLabel3", "jLabel2", PaneConstraints.RIGHT, 0.5532646f));
  }
  //File | Exit action performed
  public void jMenuItemClear_actionPerformed(ActionEvent e) {
    System.exit(0);
  }
  //Help | About action performed
  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      jMenuItemClear_actionPerformed(null);
    }
  }
  public void run() {

  }  //end of run

  public static void notifyRoom(){//监视聊天窗口的连接变化,不
    //断刷新clients数组并刷新用户列表信息
   StringBuffer people=new StringBuffer("PEOPLE");
   for(int i=0;i<clients.size();i++)
   {
     Client c=(Client)clients.elementAt(i);
     people.append(":"+c.name+":"+c.ip);
   }
   sendClients(people);
  }

public static boolean  checkName(Client newClient)
  {
    for(int i=0;i<clients.size();i++)
    {
      Client c=(Client)clients.elementAt(i);
      if((c!=newClient)&&c.equals(newClient.name))
        return false;
    }
    return true;
  }

  public synchronized void disconnect(Client c)//缺少static
  {
    try{
    int k=0;
     jTextArea2.append("系统消息: "+c.name+"   "+c.ip+"   断开连接");
     active_connects--;  //连接数减1
     jTextField1.setText("目前已经有"+active_connects+"用户连接");
     c.send(new StringBuffer("QUIT"+":"+c.name+":"+c.ip));
         //向客户发送断开信息
     c.socket.close();//断开连接
   }
   catch(IOException e)
   {
     jTextArea2.append("系统消息:"+"Error "+e);
   }
   finally{
     clients.removeElement(c);
   }
  }

  public static synchronized void sendClients(StringBuffer msg)
  {
   for(int i=0;i<clients.size();i++){
   Client c=(Client)clients.elementAt(i);
   c.send(msg);
   }
  }

  public void sendtoClient(StringBuffer msg,String name)  //将信息发送到单个用户
     {
       for(int i=0;i<clients.size();i++)
    {
      Client c=(Client)clients.elementAt(i);
      if(c.name==name)
      {
       c.ps.println(msg);
       c.ps.flush();
        break;
      }
      else i++;
    }

     }


  public void closeAll()//缺少static
  {
    while(clients.size()>0)
    {
      Client c=(Client)clients.firstElement();
      try{
        c.socket.close();
      }
      catch(IOException e){
        jTextArea2.append("系统消息:"+"     聊天服务器"+ "   Error  "+e);
      }
      finally{
        clients.removeElement(c);//从clients数组中删除客户相关的socket信息

      }
    }
  }
private class Client extends Thread{
      String name;      //用来存储客户的连接姓名
      String ip;         //用来存储客户的连接IP
      DataInputStream dis;  //用于实现接受从客户端发送来的数据流
      PrintStream ps;  //用来实现向客户端发送信息的打印流
      Socket socket;

      public  Client(Socket s)       //Client 线程的构造器
     {
      socket=s;
        try{
             dis=new DataInputStream(s.getInputStream());  //存储特定客户socket的输入流,
                                                           //接受s客户发送到服务器端的信息
             ps=new PrintStream(s.getOutputStream());    //存储特定客户socket的输出流,
                                                           //发送服务器给s客户的信息

              String info=dis.readLine();              //读取接受来的信息
              StringTokenizer stinfo=new StringTokenizer(info,":"); //读取用":"分开的分段字符
              String head=stinfo.nextToken();   //用head存储关键字的头信息
               if(stinfo.hasMoreTokens())
                name=stinfo.nextToken();         //关键字的第二个数据段是客户的名称
               if(stinfo.hasMoreTokens())
                  ip=stinfo.nextToken();        //关键字的第三个数据段是客户的IP地址
                // jTextArea2.append(head);
                 }
      catch(IOException e){
        jTextArea2.append("系统消息:"+"     聊天服务器"+"Error  "+e);
      }
  }

      public void send(StringBuffer msg)                   //实现向客户端发送信息的方法
        {
        ps.println(msg);                                  //用打印流发送信息
        ps.flush();
      }


    public void run(){            //线程的运行方法
        while(true){
          String line=null;
          try{
            line=dis.readLine();       //读取客户端发送的数据流

          }
          catch(IOException e)
          {
            jTextArea2.append("系统消息:"+"     聊天服务器"+"  Error:  "+e);
            disconnect(this);
            notifyRoom();
            return ;
          }
          if(line==null)        //客户已经离开
          {
            disconnect(this);
            notifyRoom();
            return;
          }
          StringTokenizer st=new StringTokenizer(line,":");
          String keyword=st.nextToken();//存储关键字,判断消息类型
          String broadcast=st.nextToken();//存储消息是属于广播,还是属于单播
                                          //如果单播,则记录的是目标用户名
          if(keyword.equalsIgnoreCase("MSG"))  //如果关键字是MSG,则是客户端发送的聊天信息
          {
            StringBuffer message=new StringBuffer("MSG:");//在服务器端建立一个缓冲区,用于信息的发送
            message.append(st.nextToken("\0"));
            if(broadcast.equalsIgnoreCase("BROAD"))
            {
              sendClients(message);
            }
            else
            {
              sendtoClient(message,broadcast);
            }
          }
          else if(keyword.equalsIgnoreCase("QUIT"))   //如果关键字是QUIT,则是客户端发送的退出信息
          {
            disconnect(this);
            notifyRoom();
            this.stop();
          }
        }
    }
    }

  void send_actionPerformed(ActionEvent e) {
  StringBuffer info=new StringBuffer("INFO");
  info.append(":"+"ALL"+":");
  info.append(jTextField2.getText());
  sendClients(info);
  jTextField2.setText("");
  }


  void sysexit_actionPerformed(ActionEvent e) {
   sendClients(new StringBuffer("QUIT"+":"+"Server"));
   closeAll();
   System.exit(0);
  }

  void link_actionPerformed(ActionEvent e) {
    //进行服务器的初始化建立
     if (serverSocket == null) {
        try {
          serverSocket = new ServerSocket(4000);
          jTextArea2.append("系统提示:       聊天服务器       系统开始启动......\n");
        }
        catch (IOException ee) {
          jTextArea2.append("系统消息:       聊天服务器        "+ e.toString() + "\n");
        }
      }
      if(serverSocket!=null){
       jTextArea2.append("系统消息:            已经连接\n");
        watch();
      }
  }
public void watch(){
  while(true){
        /*if(clients.size()<20)//当客户数目小于20的时候开始连接
        {*/
          try{
            socket=serverSocket.accept();//用来存储连接上的客户socket
            if(socket!=null){
            jTextArea2.append("系统消息:     "+socket.toString()+"       已经连接\n");
            }
          }
          catch(IOException ee){
          jTextArea2.append("系统消息:     聊天服务器        "+ee.toString()+" 用户连接失败\n");
          }

   int i=0;
     do{
       Client c=new Client(socket);//定义并实例化一个Client线程,每一个线程对应一个客户连接
       if(checkName(c))
       {
       clients.addElement(c);//加入到clients数组中
       active_connects++;//连接数目加1
       jTextField1.setText("目前已经有"+active_connects+"用户连接");//在状态栏中显示目前的活动数目
       Client listdata=(Client)clients.elementAt(i);
       list1.add(listdata.name+"  "+listdata.ip+"   连接",i);
       c.start();  //启动线程
       notifyRoom();  //监视聊天窗口的连接变化
       }
       else{
         c.ps.println("FaultName");//检查名字不合法,则在发送流中发送FaultName
         disconnect(c);  //断开连接
       }
      i++;
       break;
     }
     while(i<clients.size());
      }
      /*else{  //如果超过连接数目
        try{
          Thread.sleep(200);
        }
        catch(InterruptedException ee)
        {      }
      }
      }  //end of while*/
  }

}
class Frame1_send_actionAdapter implements java.awt.event.ActionListener {
  Frame1 adaptee;

  Frame1_send_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.send_actionPerformed(e);
  }
}

class Frame1_sysexit_actionAdapter implements java.awt.event.ActionListener {
  Frame1 adaptee;

  Frame1_sysexit_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.sysexit_actionPerformed(e);
  }
}

class Frame1_link_actionAdapter implements java.awt.event.ActionListener {
  Frame1 adaptee;

  Frame1_link_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.link_actionPerformed(e);
  }

}

⌨️ 快捷键说明

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