编程SocketJavathread.net

本文介绍了一个基于Java的Socket服务器实现,该服务器利用线程池来处理客户端连接请求,有效提高了并发处理能力。文章详细展示了Server端、线程池实现类及Client端的代码实现。
    (1)Server端
import java.io.*;
import java.net.*;
public class PooledRemoteFileServer {
   //服务器能同时处理的活动客户机连接的最大数目
    protected int maxConnections;
   //进入的连接的侦听端口
    protected int listenPort;
    //将接受客户机连接请求的 ServerSocket 
    protected ServerSocket serverSocket;
    public PooledRemoteFileServer(int aListenPort, int maxConnections) {
        listenPort= aListenPort;
        this.maxConnections = maxConnections;
    }
    public void acceptConnections() {
        try {
            ServerSocket server = new ServerSocket(listenPort, 5);
            Socket incomingConnection = null;
            while(true) {
                incomingConnection = server.accept();
                handleConnection(incomingConnection);
            }
        }
        catch(BindException e) {
            System.out.println("");
        }
        catch(IOException e) {
            System.out.println(""+listenPort);
        }
    }
    
    /**
     * 委派PooledConnectionHandler处理连接
     */
    protected void handleConnection(Socket connectionToHandle) {
        PooledConnectionHandler.processRequest(connectionToHandle);
    }
    
    /**
     * 创建maxConnections个PooledConnectionHandler并在新Thread中激活它们。
     * PooledConnectionHandler将等着处理进入的连接,每个都在它自己的Thread中进行。
     */
    public void setUpHandlers() {
        for(int i=0; i<maxConnections; i++) {
            PooledConnectionHandler currentHandler = new PooledConnectionHandler();
            new Thread(currentHandler, "Handler " + i).start();
        }
    }
    public static void main(String args[]) {
        PooledRemoteFileServer server = new PooledRemoteFileServer(1001, 3);
        server.setUpHandlers(); 
        server.acceptConnections();
    }
}


(2)实现线程池的类
import java.io.*;
import java.net.*;
import java.util.*;
public class PooledConnectionHandler implements Runnable {
    //connection是当前正在处理的 Socket 
	protected Socket connection;
	//静态 LinkedList 保存需被处理的连接,工作队列
    protected static List pool = new LinkedList();
    public PooledConnectionHandler() {}
    /**
     * 将攫取连接的流,使用它们,并在任务完成之后清除它们
     */
    public void  handleConnection() {
        try {
            PrintWriter streamWriter = new PrintWriter(connection.getOutputStream()); 
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
            String fileToRead = streamReader.readLine();
            BufferedReader fileReader = new BufferedReader(new FileReader(fileToRead));
            String line = null;
            while((line=fileReader.readLine())!=null)
                streamWriter.println(line); 
            fileReader.close();
            streamWriter.close();
            streamReader.close();
        }
        catch(FileNotFoundException e) {
            System.out.println("");
        }
        catch(IOException e) {
            System.out.println(""+e);
        }
    }
	/**
	 * 将把传入请求添加到池中,并告诉其它正在等待的对象该池已经有一些内容
	 * @param requestToHandle
	 */	
    @SuppressWarnings("unchecked")
	public static void processRequest(Socket requestToHandle) {
    	//确保没有别人能跟我们同时修改连接池
        synchronized(pool) {
        	//把传入的Socket添加到LinkedList的尾端
            pool.add(pool.size(), requestToHandle);
            //通知其它正在等待该池的Thread,池现在已经可用
            pool.notifyAll();
        }
    }
    public void run() {
        while(true) {
            synchronized(pool) {
                while(pool.isEmpty()) {
                    try {
                    	//对池上的wait()的调用释放锁,而wait()接着就在自己返回之前再次攫取该锁
                        pool.wait();//在连接池上等待,并且池中一有连接就处理它
                    }
                    catch(InterruptedException e) {
                        e.printStackTrace(); 
                    }
                }
                //恰巧碰上非空池的处理程序将跳出while(pool.isEmpty())循环并攫取池中的第一个连接
                connection= (Socket)pool.remove(0); 
            }
            handleConnection();
        }
    }
}

(3)Client端
import java.io.*;
import java.net.*;
/**
 *   用您想连接的机器的 IP 地址和端口实例化 Socket。
 *   获取 Socket 上的流以进行读写。
 *   把流包装进 BufferedReader/PrintWriter 的实例,如果这样做能使事情更简单的话。
 *   对 Socket 进行读写。
 *   关闭打开的流。 
 * @author Administrator
 */
public class RemoteFileClient {
    protected BufferedReader socketReader;
    protected PrintWriter socketWriter;
    protected String hostIp;
    protected int hostPort;
    /**
     * 构造方法
     */
    public RemoteFileClient(String hostIp, int hostPort) {
        this.hostIp = hostIp;
        this.hostPort=hostPort; 
    }
    /**
     * 向服务器请求文件的内容,告诉服务器我们想要什么文件并在服务器传回其内容时接收该内容
     */
    public String getFile(String fileNameToGet) {
        StringBuffer fileLines = new StringBuffer();
        try {
            socketWriter.println(fileNameToGet);            
            socketWriter.flush();
            String line = null;
            while((line=socketReader.readLine())!=null)
                fileLines.append(line+"\n");
        }
        catch(IOException e) {
            System.out.println("Error reading from file: "+fileNameToGet);
        }
        return fileLines.toString();
    }
    /**
     * 连接到远程服务器,创建我们的 Socket 并让我们访问该套接字的流
     */
    public void setUpConnection() {
        try {
            Socket client = new Socket(hostIp,hostPort);
            socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            socketWriter = new PrintWriter(client.getOutputStream());
        }
        catch(UnknownHostException e) {
            System.out.println("Error1 setting up socket connection: unknown host at "+hostIp+":"+hostPort);
        }
        catch(IOException e) {
            System.out.println("Error2 setting up socket connection: "+e);
        }
    }
    /**
     * 使用完毕连接后负责“清除”。
     */
    public void tearDownConnection() {
        try {
            socketWriter.close(); 
            socketReader.close();
        }catch(IOException e) {            
            System.out.println("Error tearing down socket connection: "+e);
        }
    }
    public static void main(String args[]) {
        RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1",1001);
        remoteFileClient.setUpConnection();
        StringBuffer fileContents = new StringBuffer();
        fileContents.append(remoteFileClient.getFile("D:/test.txt"));        
        //remoteFileClient.tearDownConnection();
        System.out.println(fileContents);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值