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

📄 server.java

📁 聊天室源码
💻 JAVA
字号:
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class Customer implements Serializable              //封装登录信息
{
	String custName;
	String custPassword;
}

 
class Register_Customer  implements Serializable //封装注册信息
{
     String custName;
     String custPassword;
     String sex;
     String email;
     String add;
     String phone;
     String age;
     
}  
class Message implements Serializable              //用于发送聊天和在线用户的信息  
{
  	Vector userOnLine;
  	Vector chat;
}
 
class Chat implements Serializable                 //聊天信息序列化
{
	String  chatUser;
	String  chatMessage;
	String  chatToUser;
	boolean whisper;
}  
 
class Exit1 implements Serializable               //退出信息序列化
{
    String exitname;	
}

public class Server extends Thread                  //创建服务器
{
	ServerSocket serverSocket;                     //设置服务器套接字
	static Vector wjn=new Vector(1,1);           // 建立动态数组
	static Vector wj=new Vector(1,1);
	
	public Server()
	{
	 try
	 {
	  serverSocket = new ServerSocket(2008);
				
			 
	InetAddress address = InetAddress.getLocalHost();      
	        
   System.out.println("主机名称:"+address.getHostName());        //获取服务器的主机名和IP地址
   System.out.println("IP地址:"+address.getHostAddress());       //在DOS界面上显示IP
		}
		catch(IOException e)
		{
			fail(e,"不能启动服务!");
		}
		
		 
		     System.out.println("");
			 System.out.println(" 欢迎进入\n ");
			 System.out.println("服务器已经启动\n.");
     	     
			 this.start();                                            //启动线程
	}
	
	public static void fail(Exception e,String str)
	{
		System.out.println(str+"."+e);
	}
	
	
 
	public void run()                                                        //监听客户的请求
	{
		try
		{
			while(true)
			{
			 
				Socket client = serverSocket.accept();                       //接受客户套接字
			    Connection con = new Connection(client,wjn,wj);          //线程通讯定义
			}
		}
		catch(IOException e)
		{
			fail(e,"不能监听!");
		}
    }
    
    
    
    public static void main(String args[])                                   //启动服务器
    {
    	new Server();
    }
}


 
class Connection extends Thread                                              //处理线程
{
	protected Socket netClient;
	
	Vector userOnline;    //在线用户信息
	Vector userChat;   
	
	protected ObjectInputStream fromClient;                                   //从客户到服务器
	protected PrintStream toClient;                                          //传导客户端
	static Vector  vList = new Vector();                                      //动态数组                      
	
	Object obj;
	
	public Connection(Socket client,Vector wjn,Vector wj)                 //通讯连接
	{
		netClient = client;
		userOnline=wjn;
		userChat=wj;
		
		try                                                                   //发生双向通信
		{		 
			fromClient = new ObjectInputStream(netClient.getInputStream());   //检索客户输入									                                   
			toClient = new PrintStream(netClient.getOutputStream());          //服务器写到客户
		}
		catch(IOException e)                                                  //输入输出文件流异常处理?
		{
			try
			{
				netClient.close();                                            //关闭netClient
			}
			catch(IOException e1)
			{
				System.out.println("不能建立文件流"+e1);                           
				return;
			}			
		}
		this.start();                                                         //线程启动
	}
	
	public void run()
	{
	 try
	{ 
			obj = (Object)fromClient.readObject();                             //建立Object对象
			if(obj.getClass().getName().equals("Customer"))                    //定义登录
			{
			    serverLogin();	
			}
	    	if(obj.getClass().getName().equals("Register_Customer"))          //定义注册
			{
			    serverRegiste();	
			}    
		    if(obj.getClass().getName().equals("Message"))                    //定义发送信息
		    {
		        serverMessage();
		    }
		    if(obj.getClass().getName().equals("Chat"))                       //定义聊天
		    {
		        serverChat();
		    }
		    if(obj.getClass().getName().equals("Exit1"))                      //定义退出
		    {
		        serverExit();	
		    }	
		}
		catch(IOException e)                                                  //捕获异常
		{
			System.out.println(e);
		}
		catch(ClassNotFoundException e1)
		{
			System.out.println("读对象发生错误!"+e1);
		}
		finally                                                         ////退出循环,执行关闭客户端
		{
			try
			{
				netClient.close();                                      // 关闭线程,退出循环
			}
			catch(IOException e)                                        //进行异常处理
			{
				System.out.println(e);
			}
		}
	}
	
	public void serverLogin()                                                  // 登录处理
	{
	    
	    try
	    {
	    	Customer clientMessage2 = (Customer)obj;
	    			    	
		    FileInputStream file3 = new FileInputStream("String.txt");         //读文件
		    ObjectInputStream objInput1 = new ObjectInputStream(file3);
		    vList=(Vector)objInput1.readObject(); 
			    	
		    int find=0;                                                        //查找判断标志
		    for(int i=0;i<vList.size();i++)
		    {     
		    Register_Customer reg=(Register_Customer)vList.elementAt(i);
		          
		   if ( reg.custName.equals(clientMessage2.custName) )             //确认用户的验证
		     {
		       find=1; 
	      if( !reg.custPassword.equals(clientMessage2.custPassword) )     //确认密码的验证
		     {
	         toClient.println("密码不正确");
	      break;
	           }
	          else
	         {		      	        
     	        int login_flag=0;                                         //判断是否已经登录
     	        for(int a=0;a<userOnline.size();a++)
	      	        {
          if(	clientMessage2.custName.equals(userOnline.elementAt(a)))   //判断动态数组
            {
  	            	login_flag=1;
           	break;                                                         //中断
    	            }
     	        }
		      	        
  	        if (login_flag==0)
   	        {
  	            userOnline.addElement(clientMessage2.custName);  //将该用户名何在
   	            toClient.println("登陆成功");
   	            Date t=new Date();                               // 在服务器端显示登录时间时期
   	            System.out.println("用户"+clientMessage2.custName+"登陆成功,"+
                                   "登陆时间:"+t.toLocaleString()+"\n");
      	            break;
       	        }
      	        else
       	        {
     	            toClient.println("该用户已登陆");                     //显示登录成功
      	        }
           } 
       }
		       else
		       {
		           continue;	                                          //中断循环开启
		       }    
		    }
		    if (find == 0)                                                 // 判断是否注册
		    {
		  	    toClient.println("没有这个用户,请先注册");
	        }
	        
	        file3.close();                                                  // 关闭流文件
		    objInput1.close();
		    fromClient.close();	
	    }
	    catch(ClassNotFoundException e)                                
  		{
  			System.out.println(e);
  		}
  		catch(IOException e)
  		{
  			System.out.println(e);
  		}
	}
	
	
     public void serverRegiste()                                    // 注册处理
    {
     try
     {
       int flag=0;                                                  //是否重名判断标志
       Register_Customer clientMessage =(Register_Customer)obj;
       File fList=new File("String.txt");
      if(fList.length()!= 0)                                        //判断是否是第一个注册用户
      {
         
	ObjectInputStream objInput = new ObjectInputStream(new FileInputStream(fList));
	vList=(Vector)objInput.readObject();                             //判断是否有重名

	for(int i=0;i<vList.size();i++)
	{
	 Register_Customer reg=(Register_Customer)vList.elementAt(i);    // 重名判断  
     if(reg.custName.equals(clientMessage.custName))
         {
          toClient.println("注册名重复,请另外选择");
           flag=1;
             break;
          }
	}
       }
      if (flag==0)                                                    //添加新注册用户
      {
	vList.addElement(clientMessage);

	FileOutputStream file = new FileOutputStream(fList);               //将向量中的类写回文件
	ObjectOutputStream objout = new ObjectOutputStream(file);
	objout.writeObject(vList);
		        toClient.println(clientMessage.custName+"注册成功");   //发送注册成功信息
		        Date t=new Date();
		        System.out.println("用户"+clientMessage.custName+"注册成功, "+
		                           "注册时间:"+t.toLocaleString()+"\n");
				    
		        file.close();                                         // 流文件关闭
		        objout.close();
		        fromClient.close();
		    }
	    }
	    catch(ClassNotFoundException e)                              //进行异常处理
  		{
  			System.out.println(e);
  		}
  		catch(IOException e)
  		{
  			System.out.println(e);
  		}
    }
    public void serverMessage()                      // 发送信息处理
    {
        try
        {
            Message mess=new Message();              //判断信息流文件
            mess.userOnLine=userOnline;
            mess.chat=userChat;
        
            ObjectOutputStream outputstream=new      // 读取输入输出流
            ObjectOutputStream(netClient.getOutputStream());
            outputstream.writeObject((Message)mess);
            
            netClient.close();                       //关闭文件流
            outputstream.close();
        }    
        catch(IOException e)
  	  	{
  	  	}
        
    }
    
   
	public void serverChat()                        //增加信息处理
  	{
  		Chat cObj = new Chat();                     //将接收到的对象值赋给聊天信息的序列化对象
  		cObj = (Chat)obj;
  		userChat.addElement((Chat)cObj);            //将聊天信息的序列化对象填加到保存聊天信息的矢量中
  		return;
  	}	   
  	public void serverExit()                        //用户退出处理 
  	{
  		Exit1  exit1=new Exit1();
  		exit1=(Exit1)obj;
  		  		
  		userOnline.removeElement(exit1.exitname);   //显示推出时间时期
  		Date t=new Date();
  		System.out.println("用户"+exit1.exitname+"已经退出, "+
  		                   "退出时间:"+t.toLocaleString()+"\n");
  	}
}

⌨️ 快捷键说明

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