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

📄 server.java

📁 用JAVA实现一个聊天室 可以实现群聊跟单聊 可以显示多个人在线
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;

public class Server 
{
	Frame f=new Frame("服务器");
	TextArea ta=new TextArea("",20,40);//显示消息框框
	TextField tf1=new TextField(20);//服务器编辑消息的框框
	Button b1=new Button("发送");//发送按钮
	TextField port=new TextField("4444",2);//设置服务器端口与客户端相同
	Button b2=new Button("启动");//启动按钮
	List yonghu=new List(20);
	ServerSocket server;
     Hashtable hash=new Hashtable();
	
	public Server()
	{
	  ta.setBackground(Color.white);
      ta.setForeground(Color.black);
      //ta.setEditable(false);
    
      Panel pta=new Panel();
      pta.add(ta);
      f.add(pta,BorderLayout.NORTH);
      
      
      Panel p=new Panel(new FlowLayout(FlowLayout.LEFT));
      //p.add(lbport);
      p.add(port);
      p.add(b2);
      p.add(tf1);
      p.add(b1);
      
     f.add(p,BorderLayout.SOUTH);
     
     Panel p1=new Panel();
     yonghu.add("所有用户");
     p1.add(yonghu);
     
     f.add(p1,BorderLayout.EAST);
     
     
      Panel p3=new Panel(new BorderLayout());
      p3.add(ta,BorderLayout.NORTH);
      p3.add(p,BorderLayout.CENTER);
      Panel p4=new Panel(new BorderLayout());
      yonghu.setBackground(Color.white);
      yonghu.setForeground(Color.black);
      p4.add(yonghu,BorderLayout.NORTH);
      
      f.add(p3,BorderLayout.CENTER);
      f.add(p4,BorderLayout.EAST);
     
     
     f.setResizable(false);//不能调节窗口大小
     f.setSize(600,40);
     
     
    f.addWindowListener(new MyActionListener());
    b1.addActionListener(new MyActionListener());//给发送按钮添加事件处理器
    b2.addActionListener(new MyActionListener());//给启动按钮添加事件处理器
    
   
    f.pack();
    f.setVisible(true);
    
     
     
	}
	
	
	public static void main(String args[])
	{
		Server s=new Server();
		
	}
	
	
	public void showUserList(){
       yonghu.clear();
       Collection col=hash.keySet();
       Iterator it=col.iterator();
       int i=0;
       while(it.hasNext()){
            String name=(String)it.next();
            yonghu.add(name);
            i++;
       }
       f.setTitle("聊天室服务器端-当前在线"+i+"位用户");
    }
    //广播消息
    public void broadCast(String msg) {

        Collection col=hash.values();
        Iterator it=col.iterator();
        while(it.hasNext()){
            try {
                Socket c = (Socket) it.next();
                OutputStream os = c.getOutputStream();
                PrintStream ps = new PrintStream(os);
                ps.println(msg);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        }
	
	
	
	
 //内部类,做事件处理
    class MyActionListener extends WindowAdapter implements ActionListener{
       Service service = new Service();
        public void actionPerformed(ActionEvent e) {
            String cmd = e.getActionCommand();
            if(cmd.equals("启动")){
                String tmp=null;
                try {
                    if(server!=null&&!server.isClosed())
                        server.close();
                    server = new ServerSocket(Integer.parseInt(port.getText()));
                    service.start();
                    tmp="启动成功\n";
                } catch (Exception ex) {
                    tmp="启动失败";
                    //ex.printStackTrace();
                }
                ta.setText(tmp);
            }
            if(cmd.equals("发送")){
            	
            	
                broadCast("[群主]:"+tf1.getText());
               ta.append("[群主]:"+tf1.getText()+"\n");
            }
          //  if(cmd.equals(" 刷 新 用 户 列 表 "))
               // showUserList();
        }
        public void windowClosing(WindowEvent e){
            System.exit(0);//关闭窗口,退出程序
        }
    }
    
    //接受连接客户端
    class Service extends Thread {
        public void run() {
           while (true) {
                try {
                    Socket client = server.accept();
                    ServiceUnit unit=new ServiceUnit(client);
                    unit.start();

                    Thread.sleep(100);
                } catch (Exception ex) {
                    //ex.printStackTrace();
                    break;
                }
                }
        }
    }
    
    
    //接受客户端聊天信息
    class ServiceUnit extends Thread{
        Socket client = null;
        InputStream is = null;
        BufferedReader br = null;
        String msg = null;
        String returnMsg=null;
        int index=0;
        String name=null;
        public ServiceUnit(Socket c) {
            client=c;
        }
        public void run() {
            //users.add(client);
            while (true) {
                try {
                    is = client.getInputStream();
                    br = new BufferedReader(new InputStreamReader(is));
                    msg = null;

                    while ((msg = br.readLine()) != null) {
                        index++;
                        if (index == 1) {
                            name = msg+"-"+client.getInetAddress().getHostAddress();
                            ta.append("[" + name + "]进入聊天室\n");
                            returnMsg = "[版主]:欢迎" + name + "进入聊天室";
                            //把登陆的用户和信息封装到一个hashtable(K,V)里
                            hash.put(name,client);
                            showUserList();
                        } else {
                            ta.append("[" + name + "]:" + msg + "\n");
                            returnMsg = "[" + name + "]:" + msg;
                        }
                        broadCast(returnMsg);
                    }
                    Thread.sleep(100);
                } catch (Exception ex) {
                    //ex.printStackTrace();
                    break;
                }
            }
            hash.remove(name);
            broadCast("[" + name + "]走了");
            ta.append("[" + name + "]走了\n");
            showUserList();
        }
    }
    
    	
	
	
}

⌨️ 快捷键说明

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