BIO of Handwritten Tomcat Series

Keywords: socket

target

Understanding what BIO is, understanding the limitations of BIO

 

understand

BIO: block I/O, synchronous blocking, server implementation mode is a connection thread, that is, when the client has a connection request, the server needs to start a thread for processing, if the connection does nothing, it will cause unnecessary thread overhead.

Limitation: Too many concurrent servers will hang up and respond slowly to requests up to or down to 1000

 

Core code

Server side

public void createLink() {
	try {
		ServerSocket ss = new ServerSocket(8888);
		System.out.println("Server has been started");
		Socket client = null;
		while (true) {
			System.out.println("BIO Service Connection Monitoring...");
			client = ss.accept();
	        System.out.println("Client"+client.getInetAddress().getLocalHost()+"Connected to the server");
			doSomething(client);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

private static void doSomething(Socket client) {
	InputStream in = null;
	OutputStream os = null;
	try {
		in = client.getInputStream();
		byte[] buff = new byte[1024];
		int len = in.read(buff);
		if (len > 0) {
			String msg = new String(buff, 0, len);
			System.out.println("The client sends information:"+msg);
	        os = client.getOutputStream();
	        os.write("Synchronized blocking service".getBytes());
			System.out.println("Information returned to the client!");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		try{
			if(null!=in) in.close();
			if(null!=os) {
		        os.flush();
		        os.close();
			}
			if(null!=client) {
				client.close();
				client = null;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

Client

public void createClient() {
		Socket s = null;
		try {
			s = new Socket("127.0.0.1", 8888);
			System.out.println("Successful server connection...");
			doSomething(s);
		} catch (ConnectException e) {
			System.err.println("Server connection failed...");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
				if(null!=s) s.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void doSomething(Socket s) {
		InputStream is = null;
		OutputStream os = null;
		try {
			if (null!=s) {
				os = s.getOutputStream();
				os.write("SocketClient1".getBytes());
				is = s.getInputStream();
				byte[] buff = new byte[1024];
				int len = is.read(buff);
				if (len > 0) {
					String msg = new String(buff, 0, len);
					System.out.println("Server returns information:"+msg);
				}else {
					System.out.println("No information returned to the server!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
				if(null!=is)is.close();
				if(null!=os) {
			        os.flush();
			        os.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

 

Posted by jameslynns on Thu, 03 Oct 2019 07:11:54 -0700