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

📄 clientthreadpoolbuilder.java

📁 JAVA实现的聊天工具,可以容纳最多10个用户 1.本系统需要JDK1.5 或更高版本的支持。 2.serverDatabase为服务器端的数据文件. 若使用现有数据,可用帐号:1, 密码
💻 JAVA
字号:
//thread called when log-in successful;to setup thread-pool
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class ClientThreadPoolBuilder implements Runnable{
	private static int threadPoolSize=10;
	private String serverAddress;
	private long currentClientID;
	private ServerSocket clientSocket = null;
	private Socket tempSocket=null;
	private static boolean signal = true;
	private boolean initiate;
	private static ExecutorService tpes;
	private Thread[] threadPool;
	private Thread controlThread; //because listen on port can fail,so ServerControlGUI is to be started here,
								 //receiving argument indicating listen on port fail or not
	public ClientThreadPoolBuilder(long currentClientID,String serverAddress){
		this.currentClientID=currentClientID;
		this.serverAddress=serverAddress;
		initiate=true;
	}
	
	public void run(){
		setupThreadPool();
		listen();
	}
	
	static void exit(){
		signal=false;
		tpes.shutdown();
		Client.exit();
	}
	
    //thread pool to handle request from clients and server
	private void setupThreadPool(){
		tpes = Executors.newFixedThreadPool(threadPoolSize);
		threadPool = new Thread[threadPoolSize];
		for(int i=0;i<threadPoolSize;i++){
			ClientThread ct=new ClientThread();
			threadPool[i]=new Thread(ct,"ClientThread"+i);
			tpes.execute(threadPool[i]);
		}		
	}
	
	private void listen(){
		try{
			clientSocket=new ServerSocket(4445); //listen port 4445 for inform from server and friends
		}catch (IOException e) {
			initiate=false;
            //System.err.println("Could not listen on port: 4445.");            
        }
		
		controlThread=new Thread(new ClientControlGUI(currentClientID,serverAddress,initiate),"ClientControlThread");
		controlThread.start();
		
		if(!initiate)
    		return;
        
        while(signal){
        	try{
        		tempSocket=clientSocket.accept();        		
        	}catch(IOException e){
        		System.out.println(e+" Server "+e.getMessage());
        	}
        	ClientThread.processRequest(tempSocket);
        }        
	}
}

⌨️ 快捷键说明

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