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

📄 chatserver.java

📁 用java编写的一个聊天工具(有源代码)
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
  }

  public static void notifyquit(String name)
  { StringBuffer quit=new StringBuffer("QUIT:");
  	quit.append(name);
	sendClients(quit);            
  }
  
  public static void notifyconnect(String name)
  { StringBuffer con=new StringBuffer("CONNECT:");
  	con.append(name);
	sendClients(con);   
  }

  //用sendClients方法向客户端发送信息
  public static synchronized void sendClients(StringBuffer msg)   //实现sendClients方法专用来向每个连接的客户端发送信息
  { for(int i=0;i<clients.size();i++)
	{ Client c=(Client)clients.elementAt(i);
	  c.send(msg);
	}
  }
  
  public static synchronized void sendClient(String from,String to,StringBuffer msg)  //向单个客户发悄悄话
  { from=from.trim();
    to=to.trim();
    for(int i=0;i<clients.size();i++)
	{ Client c=(Client)clients.elementAt(i);
	  String name=(c.name).trim();
	  if(name.equals(from)||name.equals(to))
	  {  c.send(msg);
	  }
	}
  }
  
  public static synchronized void sendClient(String to,StringBuffer msg)
  { to=to.trim();
    for(int i=0;i<clients.size();i++)
	{ Client c=(Client)clients.elementAt(i);
	  String name=(c.name).trim();
	  if(name.equals(to))
	  { c.send(msg);
	    break;
	  }
	}	
  }

  public static void closeAll()                             //实现关闭所有连接信息
  { while(clients.size()>0)                                 //遍历clients数组删除所有连接客户信息
	{ Client c=(Client)clients.firstElement();
	  try
	  { c.socket.close();
	  }
	  catch(IOException e)
	  { System.out.println("Error:"+e);
	  }
	  finally
	  { clients.removeElement(c);
	  }
	}//end of while
  }//end of closeAll method

  public static boolean checkName(Client newclient)         //实现检查连接客户的socket信息是否合法
  { 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);
  }//end of checkName method

  public static synchronized void disconnect(Client c)         //实现断开单个客户的方法
  { try
	{ jList1.addItem(c.ip+"断开连接");                      //在服务器端程序的list框中显示断开信息
	  chatServer.active_connects--;                       //将连接数减1
	  c.send(new StringBuffer("QUIT"));                    //向客户发送断开连接信息
	  c.socket.close();
	}
	catch(IOException e)
	{ System.out.println("Error:"+e);
	}
	finally
	{ clients.removeElement(c);                          //从clients数组中删除此客户的相关socket等信息
	}
  }
}

class Client extends Thread                              //实现 Client线程类
{ Socket socket;                                       //用来存储一个连接客户的socket信息
  String name;                                         //用来存储客户的连接姓名
  String ip;                                           //用来存储客户的ip信息
  DataInputStream dis;                                 //用来实现接受从客户端发来的数据流
  PrintStream ps;                                      //用来实现向客户端发送信息的打印流
	
  public void send(StringBuffer msg)                   //实现想客户端发送信息的方法
  { ps.println(msg);                                  //用打印流发送信息
	ps.flush();
  }

  public  Client(Socket s)                             //Client线程类的构造器
  { socket=s;                                           
	try
	{ dis=new DataInputStream(s.getInputStream());  //存储特定客户socket的输入流接受s这个客户发送到服务器端的信息
	  ps=new PrintStream(s.getOutputStream());      //存储特定客户socket的输出流发送服务器给s这个客户的信息
	  byte b[]=new byte[512];
	  int count=dis.read(b);
	  StringBuffer sbuf=new StringBuffer();
	  for(int i=0;i<count;i++)
	    sbuf.append((char)b[i]);
	  String info=sbuf.toString();                   //读取接受来的信息
		   
	  StringTokenizer stinfo=new StringTokenizer(info,":");  //用StringTokenizer类来读取用":"分段字符
	  String head=stinfo.nextToken();                        //head用来存储类似于关键字的头信息
      if(stinfo.hasMoreTokens())		   
		name=stinfo.nextToken();                               //关键字后的第二段数据是客户名信息
	  if(stinfo.hasMoreTokens())
	    ip=stinfo.nextToken();                                  //关键字后的第三段数据是客户ip信息
	  System.out.println(head);                               //在控制台打印头信息
    }
	catch(IOException e)
	{ System.out.println("Error:"+e);
    }
  }//end of Client constrator

  public void run()                                           //线程运行方法
  { while(true)
	{  String line=null;
	   try
	   { byte b[]=new byte[512];
		 int count=dis.read(b);
		 StringBuffer sbuf=new StringBuffer();
		 for(int i=0;i<count;i++)
		    sbuf.append((char)b[i]); 
		 line=sbuf.toString();                          //读取客户端发来的数据流
	   }
	   catch(IOException e)
	   { System.out.println("Error"+e);
		 chatServer.disconnect(this);
		 chatServer.notifyRoom();
		 return;
	   }
       if(line==null)    //客户已离开
	   { chatServer.disconnect(this);
		 chatServer.notifyRoom();
		 return;
	   }
	   StringTokenizer st=new StringTokenizer(line,":");
	   String keyword=null;
	   keyword=st.nextToken();
       if(keyword.equals("MSG"))                          //如果关键字是MSG则是客户端发来的聊天信息
	   {  keyword=st.nextToken();
	      String fsize=st.nextToken();
	      String fcolor=st.nextToken();
	      StringBuffer msg=new StringBuffer("MSG:"+keyword+":"
	                                        +fsize+":"+fcolor+":");     //在服务器端再重新建立一个字符缓冲
		  msg.append(name);
		  msg.append(st.nextToken("\0"));
		  chatServer.sendClients(msg);                   //再将某个客户发来的聊天信息发送到每个连接客户的聊天栏中
	   }
	   //need modify
       else if(keyword.equals("REQCON"))
	   {  System.out.println("server request respond");
		  System.out.println(line);
		  String toname=st.nextToken();
		  StringBuffer msg=new StringBuffer("REQCON:");
		  msg.append(name);
		  chatServer.sendClient(toname,msg);
       }
	   else if(keyword.equals("REQEXIT"))
	   {  System.out.println("server request respond");
		  System.out.println(line);
		  String toname=st.nextToken();
		  StringBuffer msg=new StringBuffer("REQEXIT:");
		  msg.append(name);
		  chatServer.sendClient(toname,msg);
	   }
	   else if(keyword.equals("RESPOND"))
	   {  System.out.println("server respond");
		  System.out.println(line);
		  StringTokenizer resp=new StringTokenizer(st.nextToken());
		  String toname=resp.nextToken();
		  boolean agree=Boolean.parseBoolean(resp.nextToken());
		  StringBuffer msg=new StringBuffer("RESPOND:");
		  msg.append(name+" "+agree);
		  chatServer.sendClient(toname,msg);		 
	   }
	   else if(keyword.equals("MSGSEC"))                  //悄悄话
	   {  String secname=st.nextToken();
		  StringBuffer msg=new StringBuffer("MSG:");
		  keyword=st.nextToken();
	      String fsize=st.nextToken();
	      String fcolor=st.nextToken();
	      msg.append(keyword+":"+fsize+":"+fcolor+":");
		  msg.append(name);
		  msg.append(st.nextToken("\0"));
		  chatServer.sendClient(name,secname,msg);
	   }
	   else if(keyword.equals("QUIT"))                   //如果关键字是QUIT则是客户端发来断开连接的信息
	   {  chatServer.notifyquit(name);
		  chatServer.disconnect(this);                 //服务器断开与这个客户的连接
		  try
		  { Thread.sleep(2000);  
		  }
		  catch(Exception e)
		  {}               
		  chatServer.notifyRoom();                      //继续监听聊天室并刷新其他客户的聊天人名list
		  this.stop();                                       
	   }
	}
  }
}  //end of class Client

⌨️ 快捷键说明

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