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

📄 server.java

📁 java 聊天工具 包括服务器 和 客户端 类似
💻 JAVA
字号:
import java.io.* ;
import java.net.*;
import java.util.*;

class UserInfo{
	public String name;
	public String password;
	public String sex;
	public String age;
	public String city;
	public String email;
	
	public UserInfo(){
		
	}
	
	public UserInfo(String name,String password,String sex,String age,String city,String email){
		this.name = name;
		this.password = password;
		this.sex = sex;
		this.age = age;
		this.city = city;
		this.email = email;
	}
	
	public String toString(){
		return name+'\n'+password+'\n'+sex+'\n'+age+'\n'+city+'\n'+email;
	}
	
	public static UserInfo getUserInfo(String userInfoString){
		UserInfo userInfo = new UserInfo();
		String[] data = userInfoString.split("\n");
		userInfo.name = data[0];
		userInfo.password = data[1];
		userInfo.sex = data[2];
		userInfo.age = data[3];
		userInfo.city = data[4];
		userInfo.email = data[5];
		return userInfo;
	}
	
	 public static UserInfo[] getUserInfoList()throws IOException{
		File file = new File("data.txt");
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		int a = in.read()-'0';
		UserInfo[]userInfoList = new UserInfo[a];
		in.readLine();
		for(int i=0;i<userInfoList.length;i++){
			userInfoList[i] = new UserInfo();
			userInfoList[i].name = in.readLine();
			userInfoList[i].password = in.readLine();
			userInfoList[i].sex = in.readLine();
			userInfoList[i].age = in.readLine();
			userInfoList[i].city = in.readLine();
			userInfoList[i].email = in.readLine();
		}
		in.close();
		return userInfoList;
	}
	
	public static void writeUserInfoList(UserInfo[] userInfoList)throws IOException{
		File file = new File("data.txt");
		FileWriter out = new FileWriter(file);
		out.write(userInfoList.length+'0');
		out.write('\n');
		for(int i=0;i<userInfoList.length;i++){
			out.write(userInfoList[i].name);
			out.write('\n');
			out.write(userInfoList[i].password);
			out.write('\n');
			out.write(userInfoList[i].sex);
			out.write('\n');
			out.write(userInfoList[i].age);
			out.write('\n');
			out.write(userInfoList[i].city);
			out.write('\n');
			out.write(userInfoList[i].email);
			out.write('\n');
		}
		out.close();
	}
	
	public static UserInfo[] addUserInfo(UserInfo[] userInfoList,UserInfo userInfo){
		UserInfo[] newList = new UserInfo[userInfoList.length+1];
		for(int i=0;i<userInfoList.length;i++){
			newList[i] = new UserInfo(userInfoList[i].name,userInfoList[i].password,userInfoList[i].sex,userInfoList[i].age,userInfoList[i].city,userInfoList[i].email);
		}
		newList[userInfoList.length] = new UserInfo(userInfo.name,userInfo.password,userInfo.sex,userInfo.age,userInfo.city,userInfo.email);
	    return newList;
	}
}

class StringOperate{
		static public String arrayToString(String[] a){
		int len=0,index=0;
		char[] b;
	    for(int i=0;i<a.length;i++){
	    	len+=a[i].length();
	    }
	    
	    b = new char[len+a.length];
	    
	    for(int j=0;j<a.length;j++){
	    	for(int k=0;k<a[j].length();k++){
	    	   b[index] = a[j].charAt(k);
	    	   index++;
	    	}
	    	b[index] = '\n';
	    	index++;
	    }
	    
	    String c = new String(b);
	    return c;
	}
	
	static public String[] stringToArray(String a){
		String[]b;
		int num=0;
		for(int i=0;i<a.length();i++){
			if (a.charAt(i) == '\n') num++;
		}
		b = new String[num];
		
		int fromindex=0;
		for(int j=0;j<num;j++){
			b[j] = a.substring(fromindex,a.indexOf('\n',fromindex));
			fromindex = a.indexOf('\n',fromindex)+1;
		}	
		return b;
	}
	
	static public String[] arrayRemoveString(String[] a,String b){
		String[] c = new String[a.length-1];
		int index=0;
	    for(int i=0;i<a.length;i++){
	    	if(a[i].equals(b)) continue;
	    	c[index] = a[i];
	    	index++;
	    }
	    return c;
	}
}

class UserData{
	
	String[] users = null;
	int num;
	
	public UserData(int num){
		users = new String[num+1];
		this.num = num;
	}
	
	public int getIndex(String str){
		for(int i=1;i<=num;i++){
		if(users[i]==null) continue;
		if(users[i].equals(str))
		return i;
		}
		return -1;
	}
	
	public int insertUser(String str,int location){
        if(users[location]==null){
        	users[location] = str;
        	return 1;
        }
        return -1;
	}
	
	public void removeUser(String str){
		int index = this.getIndex(str);
		users[index] = null;
	}
	
	public String[] getUserList(){ //返回用户列表
		int total=0;
		for(int i=0;i<num;i++){
			if(users[i]!=null) total++;
		}
		String[] a = new String[total];
		int index = 0;
		for(int j=0;j<num;j++){
			if(users[j]!=null){
				a[index] = users[j];
				index++;
			}	
		}
		return a;
	}
	
	public void print(){
		for(int i=1;i<=num;i++){
			if(users[i]!=null){
				System.out.println(i+" : "+users[i]);
			}
		}
	}
}

class StreamData implements Serializable{
	String fromName=null;
	String toName=null;
	
	String dataType=null;
	String fontFamily=null;
	int fontSize = 0;
	int rgb = 0;
	
	int length=0;
	byte[] bytes=null;
		
	
	public StreamData(){
	}
	
	public StreamData(String fromName,String toName,String dataType,String fontFamily,int fontSize,int rgb,byte[]bytes,int length){
		this.fromName=fromName;
		this.toName = toName;
		this.dataType = dataType;
		this.fontFamily = fontFamily;
		this.fontSize = fontSize;
		this.rgb = rgb;
		this.length = length;
		this.bytes = new byte[bytes.length];
		System.arraycopy(bytes,0,this.bytes,0,bytes.length);
	}
	
	private void writeObject(ObjectOutputStream out) throws IOException{		
		out.writeUTF(fromName);
		out.writeUTF(toName);
		out.writeUTF(dataType);
		out.writeUTF(fontFamily);
		out.writeInt(fontSize);
		out.writeInt(rgb);
		out.writeInt(length);
		for(int i=0;i<length;i++)
		out.writeByte(bytes[i]);
	}
	
	private void readObject(ObjectInputStream in) throws IOException{
		fromName = in.readUTF();
		toName = in.readUTF();
		dataType = in.readUTF();
		fontFamily = in.readUTF();
		fontSize = in.readInt();
		rgb = in.readInt();
		length = in.readInt();
		bytes = new byte[length];
		for(int i=0;i<length;i++)
		bytes[i] = in.readByte();
		
	}
	
	public String toString(){
		return " fromName:"+fromName+"\n toName:"+toName+"\n dataType"+dataType+"\n bytes:"+new String(bytes)+"\n length:"+length;
	}
	
	public String getFromName(){
		return fromName;
	}
	
	public String getToName(){
		return toName;
	}
	
	public String getDataType(){
		return dataType;
	}
	
	public String getFontFamily(){
		return fontFamily;
	}
	
	public int getFontSize(){
		return fontSize;
	}
	
	public int getRgb(){
		return rgb;
	}
	
	public byte[] getBytes(){
		return bytes;
	}
	
	public void setFromName(String fromName){
		this.fromName = fromName;
	}
	
	public void setToName(String toName){
		this.toName = toName;
	}
	
	public void setDataType(String dataType){
		this.dataType = dataType;
	}
	
	public void setFontFamily(String fontFamily){
		this.fontFamily = fontFamily;
	}
	
	public void setFontSize(int fontSize){
	    this.fontSize = fontSize;
	}
	
	public void setRgb(int rgb){
		this.rgb = rgb;
	}
}



class MultiClientServer implements Runnable{
	
	//static int SerialNum = 0;
	static UserData userData = new UserData(21);
	static UserInfo[] userInfoList = null;
    static ObjectInputStream[] objectInputStream = new ObjectInputStream[21];
    static ObjectOutputStream[] objectOutputStream = new ObjectOutputStream[21];
	Socket[] socket;
	Socket mySocket;
	int SerialNum;
	StreamData data,data2,rename,login,newUser;
	
	public MultiClientServer(Socket[] ss,int i){
		socket = ss;
		SerialNum = i;
		mySocket = socket[i];
	}
	
	public void run(){
		int myNum = SerialNum++;
		String s;
		try{
			userInfoList= UserInfo.getUserInfoList();
		}catch (Exception e){
			e.printStackTrace();
		}
		try{	
	    objectInputStream[myNum] = new ObjectInputStream(mySocket.getInputStream());
	    objectOutputStream[myNum] = new ObjectOutputStream(mySocket.getOutputStream());
	    
	    data = null;
	    while(true){
	    while(mySocket.getInputStream().available()==0) {
	    	Thread.currentThread().sleep(50);
	    }
	    if(mySocket.getInputStream().available()!=0){
	    
	    data = (StreamData)objectInputStream[myNum].readObject();
	    
	    if(data.getToName().equals(new String("Server"))){ 	//每个客户端在初始的时候发名字给服务器
	    if((userData.getIndex(data.getFromName())==-1))  
	    //查找已经注册用户
	    {
	    boolean exist = false;
	    for(int i=0;i<userInfoList.length;i++){
	    	if(userInfoList[i].name.equals(data.getFromName())){
	    		exist = true;
	    	   if(userInfoList[i].password.equals(data.getFontFamily())){//密码正确
	    	   	login = new StreamData();
	    	   	userData.insertUser(data.getFromName(),myNum);//插入在线用户列表
	    	   	login = new StreamData("ServerAgree",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,userInfoList[i].toString().getBytes(),userInfoList[i].toString().getBytes().length);
	    	   	objectOutputStream[myNum].writeObject(login);
	    	   	break;
	    	   }
	    	   else{//密码不正确
	    	   	login = new StreamData("ServerDisAgree",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,new String("ServerDisAgree").getBytes(),new String("ServerDisAgree").getBytes().length);
	    	   	objectOutputStream[myNum].writeObject(login);
	    	   	break;
	    	   }
	    	}
	    }
	    if(exist ==false){//用户不存在
	    		login = new StreamData("ServerNotExist",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,new String("ServerNotExist").getBytes(),new String("ServerNotExist").getBytes().length);
	    	   	objectOutputStream[myNum].writeObject(login);
	    	}
	    }
	    else{          //重名,服务器拒绝
	           rename = new StreamData("ServerRename",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,new String("重名").getBytes(),new String("重名").getBytes().length);
	           objectOutputStream[myNum].writeObject(rename);//通知原来的客户端
	    }
	    String[] userList = userData.getUserList();
	    for(int i=0;i<userList.length;i++){//给所有的客户端发送用户列表
	    	data2 = new StreamData("Server",userList[i],"TEXT",data.getFontFamily(),data.getFontSize(),data.getRgb(),StringOperate.arrayToString(userData.getUserList()).getBytes(),StringOperate.arrayToString(userData.getUserList()).getBytes().length);
	        objectOutputStream[userData.getIndex(data2.getToName())].writeObject(data2);
	    }
	    
	    }
	    else if(data.getToName().equals(new String("ServerExit"))){ //删除退出用户列表
	    	userData.removeUser(data.getFromName());
	    	String[] userList = userData.getUserList();
	    	for(int i=0;i<userList.length;i++){
	    	data2 = new StreamData("Server",userList[i],"TEXT",data.getFontFamily(),data.getFontSize(),data.getRgb(),StringOperate.arrayToString(userData.getUserList()).getBytes(),StringOperate.arrayToString(userData.getUserList()).getBytes().length);
	        objectOutputStream[userData.getIndex(data2.getToName())].writeObject(data2);
	        }
	    }
	    else if(data.getToName().equals(new String("ServerNewUser"))){
	    	//System.out.println(data.getToName());
	    	UserInfo newUserInfo = UserInfo.getUserInfo(new String(data.getBytes()));
	    	boolean exist = false;
	    	for(int i=0;i<userInfoList.length;i++){
	    		if(userInfoList[i].name.equals(newUserInfo.name)){//用户名已经被占用
	    		newUser = new StreamData("newUserNO",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,new String("newUserNo").getBytes(),new String("newUserNo").getBytes().length);
	    	   	objectOutputStream[myNum].writeObject(newUser);
	    	   	exist = true;
	    	   	break;
	    		}
	    	}
	    	
	    	//System.out.println(exist);
	    	
	    	if(exist == false){
	    		//更新列表
	    		newUser = new StreamData("newUserYES",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,new String("newUserYES").getBytes(),new String("newUserYES").getBytes().length);
	    	   	objectOutputStream[myNum].writeObject(newUser);
	    	   	UserInfo[] newUserInfoList = UserInfo.addUserInfo(userInfoList,newUserInfo);
	    	   	userInfoList = newUserInfoList;
	    	   	UserInfo.writeUserInfoList(userInfoList); 	
	    	}
	    }else if(data.getToName().equals(new String("ServerUserInfo"))){
            
            String sentUserInfo = "null";
            
            //System.out.println(data.getFontFamily());
            
	    	for(int i=0;i<userInfoList.length;i++){
	    		if(userInfoList[i].name.equals(data.getFontFamily())){
	    			sentUserInfo = userInfoList[i].toString();
	    			break;
	    		}
	    	}
	    	
	    	//System.out.println(sentUserInfo);
	    	
	    	StreamData newUserInfo = new StreamData("UserInfo",data.getFromName(),"TEXT",data.getFontFamily(),data.getFontSize(),0,sentUserInfo.getBytes(),sentUserInfo.getBytes().length);
	    	objectOutputStream[myNum].writeObject(newUserInfo);	    	
	    }
	    else
	    {//数据不是发给服务器,则转发给其他的客户端
	    	if(userData.getIndex(data.getToName())!=-1)
	    	objectOutputStream[userData.getIndex(data.getToName())].writeObject(data);
	    }
	   
	    //userData.print();/////////////////////
	    }
	    }
//		objectOutputStream.close();
	  //  objectInputStream.close();
//	    mySocket.close();
		}catch(Exception e){
			e.printStackTrace();
	    }
   }
}


public class Server{
	public static void main(String args[]){
		int MaxClientNum = 20;
		Socket[]socket = new Socket[MaxClientNum];	
		try{
		System.out.println("Server:");
		ServerSocket server = new ServerSocket(1683);
		
		for(int i=1;i<=MaxClientNum;i++){
			socket[i] = server.accept();
			Thread t = new Thread(new MultiClientServer(socket,i));
			t.start();
		}
		server.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

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