Netty-JAVA based implementation, BIO based

Prepare to learn Netty, start with JAVA's BIO, NIO, AIO, and gradually cut into Netty's learning

BIO is the implementation of JAVA's synchronous blocking IO. When the client discovers the request, it will wait until the server completes the response to end the communication process. There will be obvious efficiency problems when the number of client requests is too large, but it is very simple and practical for simple communication implementations (such as point-to-point communication).

BIO generally has two implementations, one is 1: 1 implementation, for each client request, the server starts a thread to correspond.
Netty-JAVA based implementation, BIO based

The acceptor accepts each client's request, and then starts a thread to respond. The thread should respond to the respective request thread after completion

The client implements
package netty.bio;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**

  • BIO mode client implementation
  • @author [email protected]
  • */
    public class SocketClient {

    public static void main(String[] args) {

    Socket socket = null;
    
    PrintWriter pw = null;
    
    try {
        socket = new Socket("127.0.0.1",9999);
        pw = new PrintWriter(socket.getOutputStream(),true);
        pw.println("Hello Socket");
        socket.close();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        socket = null;
        pw = null;
        e.printStackTrace();
    }finally{
        if(socket!=null) {
            socket = null;
        }
    }

    }

}

The server implements
package netty.bio;

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

/**

  • BIO mode server implementation
  • @author [email protected]
  • */
    public class SocketServer {

    public static void main(String[] args) {

    int port = 9999;
    //创建socket通信server
    ServerSocket  server = null;
    try {
    
        server  = new ServerSocket(port);
        //创建socket对象
        Socket socket = null;
        while(true) {
            //acceptor
            socket = server.accept();
            //开启一个处理线程
            new Thread ( new SocketHandler(socket)).start();
        }
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

}

package netty.bio;

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

/**

  • Define a Socket processor that implements the Runnable interface for use in thread processing
  • @author [email protected]
  • */
    public class SocketHandler implements Runnable{

    private Socket socket = null;

    public SocketHandler(Socket socket) {

    this.socket = socket ;

    }

    @Override
    public void run() {

    //对传入的数据进行读取处理
    //读入对象
    BufferedReader in = null;
    
    try {
        //读取输入流数据
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    
        String info = null;
    
        while(true) {
            //如果已读完全部数据,跳出死循环
            info = in.readLine();
            System.out.println("接收信息:"+info+" "+System.currentTimeMillis());
            if(info == null) {
                break;
            }
    
        }
        //关闭读入流,关闭Socket
        socket.close();
        in.close();
    
    } catch (IOException e) {
        if(in!=null) {
            try {
                in.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        if(socket!=null) {
            try {
                socket.close();
            } catch (IOException e1) {
                socket = null;
                e1.printStackTrace();
            }
        }
        e.printStackTrace();
    }

    }

}

Another BIO implementation is M: N, M is the number of client requests, and N is the number of server-side processing threads. Create a connection pool on the server. By configuring the number of core connections, the maximum number of connections, and the number of waiting queues in the connection pool, the number of connections on the server side is controlled. This method is safer than the 1: 1 BIO implementation, which will avoid server-side resource exhaustion when the number of client connections is too large.

Netty-JAVA based implementation, BIO based

The client implements
package netty.vio;

/**

  • BIO M: N client and client implementation
  • @author [email protected]
  • */
    public class ClientThreadMain {

    public static void main(String[] args) {

    for(int i=0;i<800;i++) {
        Thread t = new Thread(new SocketClient());
        t.start();
    }

    }

}

Connect the server
package netty.vio once in each client thread ;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**

  • BIO mode client implementation
  • @author [email protected]
  • */
    public class SocketClient implements Runnable{

    @Override
    public void run() {
    // TODO Auto-generated method stub
    Socket socket = null;

    PrintWriter pw = null;
    
    try {
        socket = new Socket("127.0.0.1",9999);
        pw = new PrintWriter(socket.getOutputStream(),true);
        pw.println("Hello Socket");
        socket.close();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        socket = null;
        pw = null;
        e.printStackTrace();
    }finally{
        if(socket!=null) {
            socket = null;
        }
    }

    }

Server-side implementation
package netty.vio;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**

  • BIO M: N mode server implementation
  • @author [email protected]
  • */
    public class SocketServer {

    public static void main(String[] args) {

    int port = 9999;
    //创建socket通信server
    ServerSocket  server = null;
    try {
    
        server  = new ServerSocket(port);
        //创建socket对象
        Socket socket = null;
        //开一个排队请求的线程池,最大线程数50,队列数1000
        SocketHandlerPool socketHandlerPool = new SocketHandlerPool(50,1000);
        while(true) {
            //acceptor
            socket = server.accept();
            //
            socketHandlerPool.execute(new SocketHandler(socket));
        }
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

}

Define the thread processing pool
package netty.vio;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**

  • Define a pool for sorting business requests
  • @author [email protected]
  • */
    public class SocketHandlerPool {

    private ExecutorService executorService;

    // Specify the maximum number of pools and the maximum number of queues
    public SocketHandlerPool (int poolSize, int queueSize) {

    /*
     * 池核心线程数
     * corePoolSize --the number of threads to keep in the pool, 
     * evenif they are idle, unless allow Core Thread TimeOut is set
     * 最大线程数
     * maximumPoolSize -- the maximum number of threads to allow in the pool
     * 线程空闲时保持时间
     * keepAliveTime -- when the number of threads is greater than the core,
     * this is the maximum time that excess idle threads will wait for new tasks before terminating.
     * 保持时间单位
     * unit -- the time unit for the keepAliveTime argument
     * 队列数
     * workQueue-- the queue to use for holding tasks before they areexecuted. This queue will hold only the Runnable tasks 
     * submitted by the execute method.
     */
    this.executorService = new ThreadPoolExecutor(4, poolSize, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));

    }

    void Execute public (the Runnable Task) {
    // perform the actual tasks
    executorService.execute (Task);
    }

}

package netty.vio;

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

/**

  • Define a Socket processor that implements the Runnable interface for use in thread processing
  • @author [email protected]
  • */
    public class SocketHandler implements Runnable{

    private Socket socket = null;

    public SocketHandler(Socket socket) {

    this.socket = socket ;

    }

    @Override
    public void run() {

    //对传入的数据进行读取处理
    //读入对象
    BufferedReader in = null;
    
    try {
        //读取输入流数据
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    
        String info = null;
    
        while(true) {
            //如果已读完全部数据,跳出死循环
            info = in.readLine();
            System.out.println("接收信息:"+info+" "+System.currentTimeMillis());
            if(info == null) {
                break;
            }
    
        }
        //关闭读入流,关闭Socket
        socket.close();
        in.close();
    
    } catch (IOException e) {
        if(in!=null) {
            try {
                in.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        if(socket!=null) {
            try {
                socket.close();
            } catch (IOException e1) {
                socket = null;
                e1.printStackTrace();
            }
        }
        e.printStackTrace();
    }

    }

}

The above is the basic implementation of BIO in JAVA. Later, I will continue to implement AIO and NIO, and gradually transition to Netty.

Guess you like

Origin blog.51cto.com/4890631/2486778