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

📄 chatserver.java

📁 上传的聊天系统程序与QQ程序差不多,只是功能没有QQ那么强大
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.sql.*;

public class ChatServer extends JFrame 
{
  //以下为图形界面变量
  JPanel contentPane;
  JMenuBar jMenuBar1 = new JMenuBar();
  JMenu jMenuFile = new JMenu();
  JMenuItem jMenuFileExit = new JMenuItem();
  JMenu jMenuHelp = new JMenu();
  JMenuItem jMenuHelpAbout = new JMenuItem();
  JMenuItem jMenuKill = new JMenuItem();
  static JLabel statusBar = new JLabel();
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  BorderLayout borderLayout2 = new BorderLayout();
  JLabel jLabel1 = new JLabel();
  static java.awt.List jList1 = new java.awt.List(13); 
  JScrollPane scrollpane=new JScrollPane(jList1);
  
  //以下为网络相关变量
  static Vector clients=new Vector(10);   //用vector向量数组存储连接客户变量
  static ServerSocket server=null;        //建立服务器socket
  static int active_connects=0;           //用来存储目前连接的客户数
  static Socket socket=null;               //用来存储一个套接字连接
  
  //ChatServer main method
  public static void main(String[] args)
  {
    try
    {
       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e)
    {
       e.printStackTrace();
    }
    
    ChatServer ChatServer1=new ChatServer();      //实例化一个ChatServer类
	ChatServer1.show();
	System.out.println("Server starting ...");
	
	try
	{
	   server=new ServerSocket(1234);      //使用端口1234初始化服务器套接字
	}
	catch(IOException e)
	{
	    System.out.println("Error:"+e);
	}
	
	while(true)
	{
	   if(clients.size()<10)       //当客户数小于10个时开始连接
	   {
		   try
		   {
			  socket=server.accept();   //用来存储连接上的客户socket
			  while(true)
			  {
                 if(socket!=null)
			     {
			        System.out.println(socket+"连接");    //在控制台打印客户连接信息
			        break;
			     }
			  }
		   }
		   catch(IOException e)
		   {
			  System.out.println("Error:"+e);
		   }
		   Client c=new Client(socket);                          //定义并实例化一个Client线程类,一个就对应一个客户连接
		   if(checkName(c))                                      //调用checkName方法验证c的合法性
		   {
			  clients.addElement(c);                             //加入clients数组中
			  int connum=++ChatServer1.active_connects;          //定义connum来存储活动连接数
			  String constr="目前有"+connum+"客户相连";          //在状态栏里显示连接数
			  ChatServer1.statusBar.setText(constr);
			  Client listdata=(Client)clients.elementAt(clients.size()-1);   //将连接客户的socket信息存储进listdata数组
	          ChatServer1.jList1.addItem(listdata.ip+"连接");   //将客户socket信息写入list框
			  c.start();                                        //启动线程
			  try
			  { 
			  	 memberlist(listdata.socket);
			  }	
			  catch (Exception f){}
                                                                                
			  sendClients(c,"hi! "+c.name+"! Welcome to Chatroom!",c.name+" is coming in !");
			  notifyRoom();                                //用notifyRoom方法来监视在线好友连接变化	
		   }
		   else
		   {
			//如果名字不合法
              try
              { 
			     c.dos.writeUTF("TAKEN");
		      }
              catch(IOException e)  
              {
                 System.out.println("Error:"+e);
		      }
		      disconnect(c);
		   }
		}
		else                                   //如果clients数组超过了10个
		{
			try
			{
				Thread.sleep(200);
			}
			catch(InterruptedException e)   
			{
                System.out.println("Error:"+e);
			}
		}
	}              //end of while
  }// end of main method

  /**Construct the frame*/
  public ChatServer()                          //ChatServer类的构造器用来初始化一些UI信息
  {
     enableEvents(AWTEvent.WINDOW_EVENT_MASK);
     try 
     {
        jbInit();
     }
     catch(Exception e) 
     {
        e.printStackTrace();
     }
  }

  /**Component initialization*/
  private void jbInit() throws Exception
  {
     contentPane = (JPanel) this.getContentPane();
     contentPane.setLayout(borderLayout1);
     contentPane.setBackground(new Color(150,150,205));
     this.setSize(new Dimension(400, 300));
     this.setTitle("聊天服务器端");
     statusBar.setText("目前的连接数为:");    
     
     jMenuFile.setText("File");
     jMenuFileExit.setText("Exit");
     jMenuFileExit.setBackground(new Color(120,150,205));
     jMenuKill.setText("Kill Somebody");
     jMenuKill.setBackground(new Color(120,150,205));  
     
     jMenuFileExit.addActionListener(new ActionListener()  
     {
        public void actionPerformed(ActionEvent e) 
        {
          jMenuFileExit_actionPerformed(e);
        }
     });
     
     jMenuHelp.setText("Help");
     jMenuHelpAbout.setText("About");
     jMenuHelpAbout.setBackground(new Color(120,150,205));
     jMenuHelpAbout.addActionListener(new ActionListener()  
     {
        public void actionPerformed(ActionEvent e) 
        {
           jMenuHelpAbout_actionPerformed(e);
        }
     });
    
     jMenuKill.addActionListener(new ActionListener()  
     {
        public void actionPerformed(ActionEvent e) 
        {
           jMenuKill_actionPerformed(e);
        }
     });
    
    
    jPanel1.setLayout(borderLayout2);
    jPanel1.setBackground(new Color(150,150,205));
    jLabel1.setText("服务器端连接客户");
    jMenuFile.add(jMenuKill);
    jMenuFile.add(jMenuFileExit);
    jMenuFile.setBackground(new Color(250,250,250));
    jMenuHelp.add(jMenuHelpAbout);
    jMenuHelp.setBackground(new Color(255,255,255));
    jMenuBar1.add(jMenuFile);
    jMenuBar1.add(jMenuHelp);
    jMenuBar1.setBackground(new Color(120,150,205));
    this.setJMenuBar(jMenuBar1);
    contentPane.add(statusBar, BorderLayout.SOUTH);
    contentPane.add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jLabel1,  BorderLayout.NORTH);
    jPanel1.add(scrollpane, BorderLayout.CENTER);
    this.setResizable(false);
  
  }//end of jbinit

  /**File | Exit action performed*/
  public void jMenuFileExit_actionPerformed(ActionEvent e)   //实现退出菜单方法
  {
     sendClients(new String("QUIT"));                         //向客户端发送断开连接信息
     closeAll();                                               //调用closeAll方法关闭所有连接
     System.exit(0);
  }

  /**Help | About action performed*/
  public void jMenuHelpAbout_actionPerformed(ActionEvent e)  //实现about对话框
  {
     ChatServer_AboutBox dlg = new ChatServer_AboutBox(this);
     Dimension dlgSize = dlg.getPreferredSize();
     Dimension frmSize = getSize();
     Point loc = getLocation();
     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
     dlg.setModal(true);
     dlg.show();
  }
   /**File | Kill action performed*/
  public void jMenuKill_actionPerformed(ActionEvent e)  
  {
     String s=JOptionPane.showInputDialog("Place Input the Client name:");

     for (int i=0;i<clients.size();i++)
     { 
        Client c=(Client)clients.elementAt(i);
        if (c.name.trim().equals(s))
        {
           sendClients(c,"Warnning: you has been Killed! Please get out!","Warning: "+s+" has been killed");	
           disconnect(c,"kill");
           try
           {
              ChatServer.notifyRoom();
              break;
           }
           catch (Exception event){}
        }
  	}
  }                         
  /**Overridden so we can exit when window is closed*/
  protected void processWindowEvent(WindowEvent e)          //实现关闭服务器端程序要进行的操作
  {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) 
    {
      jMenuFileExit_actionPerformed(null);
    }
  }

  /*以下实现各种方法*/
  public static void notifyRoom()                         //用来监视连接信息,不断刷新clients数组并刷新客户端用户列表信息
  {
     String people=new String("PEOPLE");
	 for(int i=0;i<clients.size();i++)
	 {
	    Client c=(Client)clients.elementAt(i);
	    people=people+":"+c.name; 
	 }
	 sendClients(people);                                 //用sendClients方法向客户端发送信息
  }
  
  public static void memberlist(Socket s) throws Exception        //用来获取数据库中的会员信息并将所有会员显示于好友列表信息
  {
     String member=new String("MEMBER");
	 String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=G://大三下学期//java//聊天//PP2007.mdb";
	
	 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

	 Connection con = DriverManager.getConnection(url,"","");

	 Statement st = con.createStatement();
	 ResultSet rs = st.executeQuery("select * from userlist");
	 ResultSetMetaData rsmd;
	 rsmd=rs.getMetaData();
	 int numCols=rsmd.getColumnCount();
	 int numline=1;
	 while(rs.next())
	 {
	     member=member+":"+rs.getString(1)+":"+rs.getString(2)+":"+rs.getString(4);
	 }
	 rs.close();
	 st.close();
	 
	 sendClients(member,s);                                 //用sendClients方法向客户端发送信息
  }

  public static synchronized void sendClients(String msg)   //实现sendClients方法专用来向每个连接的客户端发送信息
  {
     for(int i=0;i<clients.size();i++)
	 {
	    Client c=(Client)clients.elementAt(i);
		c.send(msg);
	 }
  }
  
  public static synchronized void sendClients(String msg,Socket s)   //实现sendClients方法专用来向每个连接的客户端发送信息
  {
     for(int i=0;i<clients.size();i++)
	 {
	    Client c=(Client)clients.elementAt(i);
		if(c.socket==s)
		  c.send(msg);
	 }
  }
  
  public static synchronized void sendClients(String reciver,String msg)   //实现sendClients方法专用来向每个连接的客户端发送信息
  {
     for(int i=0;i<clients.size();i++)

⌨️ 快捷键说明

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