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

📄 chatroomserve.java

📁 c/s模式java聊天室,对初学者有很好的帮助
💻 JAVA
字号:

package newackage;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.String;
import java.lang.String;
import java.net.*;
import java.sql.Date;
import java.util.Vector;
public class ChatRoomServe extends Applet implements Runnable{
	Panel panel;
	ScrollPane sPanel;
	public static final TextArea textArea=new TextArea(5,25);
	Button button1;
	ServerSocket serverSock;
	public final static int DEFAULT_PORT=6666;// 设置默认端口号
	Thread chatAcceptThread;// 启动接受连接的线程
	BroadcastThread broadcastThread;// 广播thread; 在服务器监听的时候运行
	java.util.Vector clients;// 记录各连接的线程
	java.util.Vector clientsInfor;// 记录连接线程发送的信息
	public static int index=0;

        static boolean flag=false,flag2=false;

	public ChatRoomServe(){
		try{
			jbInit();//调用初始化函数
		}catch(Exception e){
			e.printStackTrace();
		}
		serverListen();// 服务器开始监听
	}

	private void jbInit(){// 初始化界面
		panel=new Panel();		
		button1=new Button("关闭服务器");
		button1.addActionListener(new java.awt.event.ActionListener(){// 退出按钮注册
			public void actionPerformed(ActionEvent e){
				button1_actionPerformed(e);
			}
		});
		panel.add(button1);

		//this.addWindowListener(new WindowAdapter(){//处理窗口关闭事件
		//	public void windowClosing(WindowEvent e){
		//		System.exit(0);
		//	}
		//});
		this.setSize(300,500);
		this.setLayout(new BorderLayout());
		//this.add(sPanel,BorderLayout.CENTER);
		this.add(panel,BorderLayout.SOUTH);
		this.add(textArea,BorderLayout.CENTER);
		//this.add(button1,BorderLayout.SOUTH);
		this.show();

	}

	private void button1_actionPerformed(ActionEvent e){
		exit();
	}

	public void processMsg(String str){
		textArea.append(str);
	}
	private void serverListen(){
		try{
			serverSock=new ServerSocket(DEFAULT_PORT);
		}catch(IOException e){
			processMsg(e.toString());
			processMsg("服务器失败!\n");
		}
		processMsg("正在监听端口:"+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();
                                clientsInfor.add("朋友"+i);
                                flag=true;
				CommunicateThread ct=new CommunicateThread(clientSock,this,index,flag);// 创建线程保持连接
				clients.add(ct);// 记录已连接的线程
				i++;
				//broadcastThread.broadcast ( (String) clientsInfor.get(index)); 
                                index++;				                           
                                
			}
		}catch(IOException e){
			processMsg(e.toString());
		} 
	}

	public void exit(){
		broadcastThread.broadcast("服务器已退出!");
		try{
			serverSock.close();
		}catch(IOException ioe){}
		finally{
			System.exit(0);
		}
	}

	public static void init(String[] args){//主函数
		ChatRoomServe chat=new ChatRoomServe();
	}
} 
class CommunicateThread extends Thread{// 保持连接线程
	protected Socket clientSock;
	protected BufferedReader in=null;
	protected PrintWriter out;
	ChatRoomServe chatFrame;
	boolean isTrue=true;// run()
	java.util.Vector inforStack;
	int index2;//
        boolean flag;
        
        Vector name=null;
	public CommunicateThread(Socket Sock,ChatRoomServe cFrame,int index,boolean flag){
		clientSock=Sock;
		chatFrame=cFrame;
		index2=index;
                this.flag= flag;
                chatFrame.flag=false;
              
		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=null;
		try{
			while(isTrue){
				infor=in.readLine();
                                 if(flag==true)
                                {
                                   // ChatRoomServe.flag2=true;
                                    chatFrame.clientsInfor.set(index2,new String("$$#"+infor));
                                    chatFrame.processMsg("\n"+infor+"加入");
                                    chatFrame.broadcastThread.broadcast("$$$");
                                    for(int i=0;i<=index2;i++){
                                    chatFrame.broadcastThread.broadcast ( (String) chatFrame. clientsInfor.get(i));
                                    }
                                    flag=false;
                                }
                                else
                                    if(infor.startsWith("$$$$"))
                                    for(int i=0;i<=index2;i++)
                                    {
                                    if(infor.endsWith(chatFrame.clientsInfor.get(i).toString()))
                                    {
                                        CommunicateThread sct=new CommunicateThread(clientSock,chatFrame,index2,flag);
                                          try {
                                            chatFrame.clients.get(index2).wait();
                                             } catch (InterruptedException ex) {
                                        ex.printStackTrace();
                                              }
                                    }
                                    }else
				if(infor.equals("exit")){
					writeInformation(infor);// 把信息写到信息栈,以倍广播出去
					stopRun();
				}else if(infor!=null){
					writeInformation(infor);
				}// else break;
				try{
					Thread.sleep(100);
				}catch(InterruptedException ex){}
			}
		}catch(IOException e){ ;}
		finally{
			try{
				in.close();
				out.close();
				clientSock.close();
			        chatFrame.clients.remove(index2);// 在clients中清除本线程序
				ChatRoomServe.index--;
                                chatFrame.broadcastThread.broadcast("$$$");
                                for(int i=0;i<=index2;i++){
                                chatFrame.broadcastThread.broadcast ( (String) chatFrame. clientsInfor.get(i));
                                    }
			}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{// 广播线程
	ChatRoomServe chatFrame2;
	java.util.Vector chatClients;// 连接线程信息
	java.util.Vector msgStack;// 信息栈
	java.util.Vector clientMsg;// 记录客户发送的信息
	CommunicateThread comThread1;
	CommunicateThread comThread2;
	String string;//栈中的信息
	String clientName;// 线程名字
	String broadcastInfor;// 广播出去的信息=线程名+发出的信息;

	public BroadcastThread(ChatRoomServe cFrame){
		chatFrame2=cFrame;
		chatClients=chatFrame2.clients;
		clientMsg=chatFrame2.clientsInfor;
//		this.start();
	}

	public void broadcast(String str){// 广播
		chatFrame2.processMsg(new Date(System.currentTimeMillis())+str+"\n");

		//ChatRoomServe.textArea.append(str+"\n"+new Date(1000));//在服务器端显示出聊天是的每一条信息
		for(int k=0;k<chatClients.size();k++){//分别调用每个连接线程,发送信息
			comThread2=(CommunicateThread)chatClients.get(k);
			comThread2.sendInformation(str);
                        //comThread2.sendInformation((String) clientMsg.get(k));
		}             
	}

	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);
						broadcastInfor=clientName.substring(3)+": "+string;						
                                                broadcast(broadcastInfor);                                                
					}
					// 清除信息栈
					msgStack.removeAllElements();// 清除以发送的信息

				}                              
				try{
					Thread.sleep(100);                                          
				}catch(InterruptedException ex){}
			}
		}catch(Exception e){}
	}

       
} 
class persenchat extends Thread
{    
    CommunicateThread sct, clients;
    persenchat(CommunicateThread sct,CommunicateThread clients)
    {
        this.sct=sct;
        this.clients=clients;
        this.start();
    }
    public void run()
    {
        String infor=null;
        try {
            infor=sct.in.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
         clients.out.println( "$$$$"+infor);
			while(true){
            try {
                   infor=sct.in.readLine();
                   clients.out.println( infor);
                   clients.out.flush();
                try {
                    this.sleep(300);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
                        }
				
          
    }
}

⌨️ 快捷键说明

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