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

📄 clientthread.java

📁 JAVA实现的聊天工具,可以容纳最多10个用户 1.本系统需要JDK1.5 或更高版本的支持。 2.serverDatabase为服务器端的数据文件. 若使用现有数据,可用帐号:1, 密码
💻 JAVA
字号:
//process info from server and other friends
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;
public class ClientThread implements Runnable{
	private static boolean signal=true,readingToFriendFileList=false,readingFromFriendFileList=false;
	private boolean processing=false;
	private Socket tempSocket ;
	private ObjectInputStream ois; //to receive data
	private DataInputStream dis;
	private ByteArrayInputStream bais;
	private ByteArrayOutputStream baos;
	private byte[] byteArray;
	private static List<Socket> pool;
	private static int toFriendFileNum,fromFriendFileNum;
	private static List<ToFriendFile> toFriendFileList;
	private static List<FromFriendFile> fromFriendFileList;
	
	public ClientThread(){
		pool = new LinkedList<Socket>();
		toFriendFileList=new LinkedList<ToFriendFile>();
		fromFriendFileList=new LinkedList<FromFriendFile>();
		toFriendFileNum=0;
		fromFriendFileNum=0;
	}
	
	public void run(){
		while(signal){
			synchronized(pool){
				while(pool.isEmpty()){
					try{
						pool.wait();
					}catch(InterruptedException e){
						System.out.println(e+" ClientThread "+e.getMessage());
					}
				}
				tempSocket=pool.remove(0);
				while(processing);
				processing=true;
				handleConnection();
				while(processing);
				closeSocketStreams();
			}
		}
	}
	
	synchronized static void processRequest(Socket temp){
		synchronized(pool){
			pool.add(temp);
			pool.notifyAll();
		}
	}
	
	static int getToFriendFileID(){
		return ++toFriendFileNum;
	}
	
	static int getFromFriendFileID(){
		return ++fromFriendFileNum;
	}
	
	static void addToFriendFile(ToFriendFile cf){
		toFriendFileList.add(cf);
	}
	
	/*static void addFromFriendFile(FromFriendFile cf){
		fromFriendFileList.add(cf);
	}*/
	
	static void clearFileList(){ //called when server quit from ClientControlGUI
		toFriendFileList.removeAll(toFriendFileList);
		fromFriendFileList.removeAll(fromFriendFileList);
	}
	//called by a ClientThread when receive signal from friend that he is ready to receive file
	/*synchronized static ToFriendFile getToFriendFile(int id){
		int index=Collections.binarySearch(toFriendFileList,new ToFriendFile(id));
		if(index<0)
			return null;
		else
			return toFriendFileList.remove(index);
	}
	//called by ClientThread when a client has chosen a directory for a from-friend-file
	synchronized static FromFriendFile getFromFriendFile(int id){
		int index=Collections.binarySearch(fromFriendFileList,new FromFriendFile(id));
		if(index<0)
			return null;
		else
			return fromFriendFileList.remove(index);
	}*/
	
	
	private void initiateSocketStreams(){ //initiate streams		
    	try{
    		//ois=new ObjectInputStream(/*new BufferedInputStream(*/
    				//tempSocket.getInputStream());
    		//oos=new ObjectOutputStream(/*new BufferedOutputStream(*/
    				//tempSocket.getOutputStream());
    		baos=new ByteArrayOutputStream(6000);
    		dis=new DataInputStream(tempSocket.getInputStream());
    	}catch(IOException e){
    		System.out.println(e+" ClientThread "+e.getMessage());
    	}
	}
	
	private void closeSocketStreams(){
		try{
			baos.close();
    		dis.close();
    		tempSocket.close();
    	}catch(IOException e){
       		System.out.println(e+"  ClientThread "+e.getMessage());
       	}   
	}
	
	private void handleConnection(){
		initiateSocketStreams();
    	
    	//get communicate object
    	Communicate d=null;
    	try{
    		byteArray=new byte[6000];
    		dis.read(byteArray,0,6000);
    		bais=new ByteArrayInputStream(byteArray);
    		ois=new ObjectInputStream(bais);
    		d=(Communicate)ois.readObject();
    		//for(int j=0;j<100000000;j++);  //**test
    	}catch(IOException e){
    		System.out.println(e+" !!ClientThread "+e.getMessage()+"\n");
    		e.printStackTrace();
    	}catch(ClassNotFoundException e){
    		System.out.println(e+" ClientThread "+e.getMessage());
    	}
    	//System.out.println(d);  //**test
    	if(d==null){
    		System.out.println("!!Get null data!!");  //**test
    		processing=false;
    		return;
    	}
    	String type=d.getType(); //get info type
    	
    	if(type.equals("serverQuit")){
    		serverQuit();
    	}
    	else if(type.equals("oneFriendOnline")){
    		oneFriendOnline(d);
    	}
    	else if(type.equals("onlineFriendsList")){
    		onlineFriendsList(d);
    	}
    	else if(type.equals("oneFriendQuit")){
    		oneFriendQuit(d);
    	}
    	else if(type.equals("friendWantChat")){
    		friendWantChat(d);
    	}
    	else if(type.equals("friendWantSendFile")){
    		friendWantSendFile(d);
    	}
    	else if(type.equals("readyToReceiveFile")){
    		readyToReceiveFile(d);
    	}
    	else processing=false;
	}
	
	private void serverQuit(){
		System.out.println("Server has quited.");
		closeSocketStreams(); 
		signal=false; //all ClientsThhread die naturelly
		processing=false;
		Client.getFriendsDatabase().removeAllFriends();
		ClientControlGUI.serverExit();		
	}
	
	private void oneFriendOnline(Communicate d){
		ServerClientData scd=(ServerClientData)d;
		int index,lastIndex;
		long tempID;
		String tempIP;
		String tempName;
		String idIPName;
		FriendsData fd;
		LinkedList<FriendsData> updateFriendList=new LinkedList<FriendsData>();
		
		idIPName=scd.getInfo();
		index=idIPName.indexOf(",");
		lastIndex=idIPName.lastIndexOf(",");
		//System.out.println("Index: "+index); //**test
		tempID=Long.parseLong(idIPName.substring(0,index)); //get online friend's id
		tempIP=idIPName.substring(index+1,lastIndex); //get online friend's ip
		tempName=idIPName.substring(lastIndex+1);  //get name from FriendsDatabase.friendsList		
		fd=new FriendsData(tempName,tempID,tempIP);
		if(!Client.getFriendsDatabase().contains(tempID)){//if doesn't in local database			
			Client.getFriendsDatabase().addFriend(fd);
			Client.getFriendsDatabase().sortFriendsList(); //sort
			updateFriendList.add(fd);			
		}
		else{//already in database,maybe the friend has quited and relog in from another pc
			Client.getFriendsDatabase().delFriend(tempID); //del old data
			Client.getFriendsDatabase().addFriend(fd);			
		}
		if(updateFriendList.size()!=0)
			ClientControlGUI.updateFriendList(updateFriendList);
		processing=false;
	}
	
	private void onlineFriendsList(Communicate d){ //a list of friends online
		ServerClientData scd=(ServerClientData)d;	
		List<Long> tempOnlineFriendsList=new LinkedList<Long>();
		List<String> tempOnlineFriendsIP=new LinkedList<String>();
		List<String> tempOnlineFriendsName=new LinkedList<String>();
		String tempName;
		String tempIP;
		long tempID;
		FriendsData fd;
		LinkedList<FriendsData> updateFriendList=new LinkedList<FriendsData>();
		
		tempOnlineFriendsList=scd.getFriends();
		tempOnlineFriendsIP=scd.getFriendsIP();
		tempOnlineFriendsName=scd.getFriendsName();
		
		if(tempOnlineFriendsList==null){ //if no friends online
			processing=false;
			return; 
		}
		
		//add online friends list to FriendsDatabase.friendsList
		for(int i=0;i<tempOnlineFriendsList.size();i++){
			tempID=tempOnlineFriendsList.get(i).longValue();
			tempIP=tempOnlineFriendsIP.get(i);
			tempName=tempOnlineFriendsName.get(i);
			fd=new FriendsData(tempName,tempID,tempIP);
			//System.out.println("tempID:"+tempID); //**test
			if(!Client.getFriendsDatabase().contains(tempID)){//if doesn't in local database				
				Client.getFriendsDatabase().addFriend(fd);
				updateFriendList.add(fd);
			}
			else{ //already in database,maybe the friend has quited and relog in from another pc
				//System.out.println("onlineFriendsList: to remove old data,Id:"+tempID); //**test
				Client.getFriendsDatabase().delFriend(tempID); //del the old data
				Client.getFriendsDatabase().addFriend(fd);
				Client.getFriendsDatabase().sortFriendsList(); //sort				
			}			
		}
		if(updateFriendList.size()!=0)
			ClientControlGUI.updateFriendList(updateFriendList);
		processing=false;
	}
	
	private void oneFriendQuit(Communicate d){
		ServerClientData scd=(ServerClientData)d;
		long friendID=scd.getID(); //quit-friend's id
		if(!Client.getFriendsDatabase().contains(friendID)){
			processing=false;
			return;
		}
		Client.getFriendsDatabase().friendQuit(friendID);
		ClientControlGUI.oneFriendQuit(friendID);
		processing=false;
	}
	
	private void friendWantChat(Communicate d){
		ServerClientData scd=(ServerClientData)d;
		long friendID;
		String tempName;
		String tempIP=tempSocket.getInetAddress().toString().substring(1);
		String info=scd.getInfo();
		int index=info.indexOf(",");
		friendID=Long.parseLong(info.substring(0,index));
		
		/*System.out.println("frindID:"+friendID+"\nfrinds-list:"); //**test
		Client.getFriendsDatabase().viewAllFriends();
		System.out.println();*/
		
		if(!Client.getFriendsDatabase().contains(friendID)){ //if info come from non-friend
			processing=false;
			return;
		}
		info=info.substring(index+1);
		FriendsData fd=Client.getFriendsDatabase().findFriend(friendID);
		if(fd==null)
			tempName="";
		else
			tempName=fd.getName();
		//System.out.println("Info from IP: "+tempIP+" (Name: "+tempName+" ID: "+friendID+") :"+info);
		ClientControlGUI.friendInfo(info,friendID,tempName);
		processing=false;
	}
	
	private void friendWantSendFile(Communicate d){
		ServerClientData scd=(ServerClientData)d;
		long friendID=scd.getID();
		if(!Client.getFriendsDatabase().contains(friendID)){ //if info come from non-friend
			processing=false;
			return;
		}
		String friendName=Client.getFriendsDatabase().findFriend(friendID).getName();
		String fileName=scd.getFileName();
		int sendFileKey=scd.getSendFileKey(); //key to get file from toFriendFileList on friend side
		ClientControlGUI.sendFileRequest(fileName,tempSocket.getInetAddress(),sendFileKey,friendID,friendName);
		processing=false;
	}
	
	private void readyToReceiveFile(Communicate d){
		ServerClientData scd=(ServerClientData)d;
		int sendFileKey=scd.getSendFileKey();
		int index;
		ToFriendFile tff;
		synchronized(toFriendFileList){ //use sendFileKey to get the file to send
			if(readingToFriendFileList){
				try{
					toFriendFileList.wait();
				}catch(InterruptedException e){					
				}
			}
			readingToFriendFileList=true;
			index=Collections.binarySearch(toFriendFileList,new ToFriendFile(sendFileKey));
			//System.out.println("index: "+index);
			if(index<0){
				processing=false;
				readingToFriendFileList=false;
				toFriendFileList.notifyAll();
				return;
			}			
			//tff=getToFriendFile(index);  //get file to send
			tff=toFriendFileList.remove(index);
			readingToFriendFileList=false;
			toFriendFileList.notifyAll();
		}
		//System.out.println("toFriendFileList: "+toFriendFileList);  //**test
		//System.out.println(tff);
		File tempFile=tff.getFile();  //file has been removed
		if(!tempFile.exists()){
			processing=false;
			System.out.println("file has been removed!"); //**test
			return;
		}
		
		try{
			//DataOutputStream tempDos=new DataOutputStream(tempSocket.getOutputStream());
			BufferedOutputStream tempBos=new BufferedOutputStream(tempSocket.getOutputStream());
			int t;
			FileInputStream fis=new FileInputStream(tempFile);
			BufferedInputStream bis=new BufferedInputStream(fis);
			while((t=bis.read())!=-1){
				tempBos.write(t);
			}
			tempBos.close();
			fis.close();
			bis.close();
		}catch(IOException e){
			System.out.println(e+" ClientThread "+e.getMessage());
		}
		/*JOptionPane.showMessageDialog(null,"File: "+tff.getFile().getName()+" has been sent!",
				"File-sending successful",JOptionPane.INFORMATION_MESSAGE);*/
		processing=false;
	}
}

⌨️ 快捷键说明

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