座IO理解力

         一般堵塞IO服务器通信,通常有一个单独的Acceptor线程负责监控client联系,它接收client对于每个请求连接后client分配用于处理一个新的线程,处理后。返回应答给client。线程才销毁。

         来看一下堵塞IOserver的代码:

         server启动类

package com.bio.demo.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.bio.demo.Server.handler.TimerServerHandler;

/**
 * @author zhouxuejun
 *
 * @date 2014年10月20日 下午7:08:58
 */
public class TimeServer {
	
     public static ServerSocket server=null;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			server=new ServerSocket(8080);
			Socket socket=null;
			while(true){
				socket=server.accept();
				new Thread(new TimerServerHandler(socket)).start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
	}

}

处理线程类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author zhouxuejun
 *
 * @date 2014年10月20日 下午7:17:28
 */
public class TimerServerHandler implements Runnable {

	 private Socket socket;
	 public  TimerServerHandler(Socket socket) {
		// TODO Auto-generated constructor stub
		 this.socket=socket;
	}
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
      BufferedReader in=null;
      PrintWriter out=null;
      try {
		in=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		out=new PrintWriter(this.socket.getOutputStream());
		String body=null;
		String tag=null;
		while(true){
		body=in.readLine();
		if(null==body)
			 break;
        out.print(body+"_return"); 
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		if(null!=in){
			try {
				in.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		if(null!=out){
			out.close();
			out=null;
		}
		if(null!=this.socket){
			try {
				this.socket.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			this.socket=null;
		}
		e.printStackTrace();
	}
	}

}

通过上面的代码能够看出。每当一个新的client请求过来,服务端都须要创建一个新的线程处理新接入的client请求,一个线程仅仅能处理一个client的请求。

在高性能server应用领域,往往须要面向成千上万client的并发接入。堵塞IO显然无法满足高性能,高并发现场访问。



版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4838936.html