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

📄 chatserver.java

📁 Java小项目 在线聊天室 一次java作业 代码还很清晰 用到了很多java的基础知识 io流传输,线程,awt 还是能学到很多知识的
💻 JAVA
字号:
package com.xdf.java.socket;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

import java.util.Hashtable;
import java.util.Enumeration;
public class ChatServer extends Frame{
    TextArea ta=new TextArea(20,80);//消息接收显示框
    TextField tf=new TextField(60);//消息编写框
    Button b=new Button("  发  送  ");//发送消息按钮
    Button start=new Button("启动服务");
    TextField portInput=new TextField("6688",2);
    Button refreshUser=new Button("  刷 新 用 户 列 表  ");
    ServerSocket ser;
    ChatServer win=this;
    MyWindowlis 	mwlis=new MyWindowlis();
    List userList=new List(21);
    Hashtable users=new Hashtable();
    String name = null;
    Object o1=null;
    Object o2=null;
    int countall=0;
    MyActionLis lis=new MyActionLis();
    public ChatServer() {
        super("聊天室服务器端");
        ta.setBackground(new Color(1,60,160));
        ta.setForeground(Color.white);
        ta.setEditable(false);
        //this.add(ta,BorderLayout.NORTH);
        Panel p=new Panel(new FlowLayout(FlowLayout.LEFT));
        p.add(new Label("Port"));
        p.add(portInput);
        p.add(start);
        p.add(tf);
        p.add(b);

        Panel pleft=new Panel(new BorderLayout());
        pleft.add(ta,BorderLayout.NORTH);
        pleft.add(p,BorderLayout.CENTER);
        Panel pright=new Panel(new BorderLayout());
        userList.setBackground(new Color(1,60,60));
        userList.setForeground(Color.white);

        Panel pb=new Panel();
        pb.add(refreshUser);
        
        pright.add(pb,BorderLayout.CENTER);
        pright.add(userList,BorderLayout.NORTH);
        
        tf.addActionListener(lis);
        start.addActionListener(lis);
        b.addActionListener(lis);
        refreshUser.addActionListener(lis);
        
        this.addWindowListener(mwlis);
        this.add(pleft,BorderLayout.CENTER);
        this.add(pright,BorderLayout.EAST);
      
        this.setResizable(false);//不能调节窗口大小
        this.pack();
        this.show();
    }
    public static void main(String[] args) {
        ChatServer s = new ChatServer();
    }
    private class MyWindowlis extends WindowAdapter {
        public void windowClosing(WindowEvent e) {

            System.exit(0);
        }

    }

    //内部类,事件处理(在事件处理器中不要写死循环代码,如果需要,用线程实现)
    private class MyActionLis implements ActionListener{
        PortListener portLis=new PortListener();

        public void actionPerformed(ActionEvent e){
            String cmd=e.getActionCommand();
            if(cmd.equals("启动服务")){
                try {
                    if (ser == null || ser.isClosed()){
                        ser = new ServerSocket(Integer.parseInt(portInput.getText()));
                        win.setTitle("聊天室服务器端(已启动)");
                    }
                    portLis.start();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            else if(cmd.equals("  发  送  ")){
            	String msg="[版主] :"+tf.getText();
            	ta.append(msg+"\n");
            	Socket s=new Socket();
            	Chat chat=new Chat(s);
            	 chat.broadCast(msg);
            	 tf.selectAll();
            	
            }
            else if(cmd.equals("  刷 新 用 户 列 表  ")){

            	refresh();
            	
            }else{
            	String msg="[版主]:"+tf.getText();
            	ta.append(msg+"\n");
            	Socket s=new Socket();
            	Chat chat=new Chat(s);
            	chat.broadCast(msg);
            	tf.selectAll();
            }
        }
    }
    
    public void refresh(){//刷新的方法
    	userList.clear();
    	Enumeration en=users.elements();
        int count=0;
       
    	while(en.hasMoreElements()){
        	count++;
        	String name1=(String)en.nextElement();
        	userList.add(name1);
        	System.out.println("hash里剩下的东西"+name1.toString());
        	//win.setTitle("聊天室服务器端(已启动)"+"-当前在线"+count+"位用户");	
        }
    	 win.setTitle("聊天室服务器端(已启动)"+"-当前在线"+count+"位用户");
    }

    //聊天线程(负责与具体的客户端聊天)
    private class Chat extends Thread{
        private Socket client;
        private InputStream is;
        private InputStreamReader isr;
        private BufferedReader br;
        public Chat(Socket client){
            this.client=client;
        }
        //广播消息
        private void broadCast(String msg){
            Enumeration en=users.keys();
            OutputStream os=null;
            PrintStream ps=null;
            while(en.hasMoreElements()){
                Socket client=(Socket)en.nextElement();
                if(!client.isClosed()){
                    try {
                        os = client.getOutputStream();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    ps = new PrintStream(os);
                    ps.println(msg);
                }
            }
        }
        public void run(){
            try {
                //while (true) {
                    is = client.getInputStream();
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);
                    String line = null;
                    String msg = null;
                   
                    while ((line = br.readLine()) != null) {
                        if (line.indexOf("####") == 0) {
                        	countall++;
                            name = line.substring(4, line.length());
                            msg = "[系统]" + name + "已登录";
                            users.put(client,name);//把当前客户信息加入users集合
                            userList.add(name);
                            win.setTitle("聊天室服务器端(已启动)"+"-当前在线"+countall+"位用户");
                        } else {
                        	msg = line;
                        }
                        ta.append(msg + "\n");
                        //群发消息
                        broadCast(msg);
                    }
                    Thread.sleep(20);
                //}
            } catch (Exception ex) {
               if(ex.getMessage().equals("Connection reset")){
                	//System.out.println("当遇到异常时 name为:"+name+"client 为:"+client); 
                	users.remove(client);//当遇到异常的时候 把他移出----------------------------------------------------
                	refresh();
               }               
                
            } finally{
                try {
                    //br.close();
                    //isr.close();
                    //is.close();
                    //client.close();
                } catch (Exception ex1) {
                    ex1.printStackTrace();
                }
            }
        }
    }


    //监听线程(负责监听端口,分配工作)
    private class PortListener extends Thread {
        public void run() {
            while (true) {
                try {
                    //每当监听到有客户端访问时,创建一个Chat线程,将该客户端交给它处理
                    Socket client = ser.accept();
                    Chat chat = new Chat(client);
                    chat.start();

                    Thread.sleep(20);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }
    }
}

⌨️ 快捷键说明

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