手写Tomcat系列之BIO

目标

理解什么是BIO,了解的BIO的限制

 

了解

BIO : block I/O , 同步阻塞式,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销

限制:并发太多服务器会挂掉,只要并发到1000上下响应请求就会很慢

 

核心代码

服务端

public void createLink() {
	try {
		ServerSocket ss = new ServerSocket(8888);
		System.out.println("服务端已启动");
		Socket client = null;
		while (true) {
			System.out.println("BIO服务连接监听中...");
			client = ss.accept();
	        System.out.println("客户端"+client.getInetAddress().getLocalHost()+"已连接到服务器");
			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("客户端发送了信息:"+msg);
	        os = client.getOutputStream();
	        os.write("同步阻塞式服务".getBytes());
			System.out.println("已向客户端返回信息!");
		}
	} 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();
		}
	}
}

客户端

public void createClient() {
		Socket s = null;
		try {
			s = new Socket("127.0.0.1", 8888);
			System.out.println("服务器连接成功...");
			doSomething(s);
		} catch (ConnectException e) {
			System.err.println("服务器连接失败...");
		} 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("服务端返回信息:"+msg);
				}else {
					System.out.println("未获取到服务端返回的信息!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
				if(null!=is)is.close();
				if(null!=os) {
			        os.flush();
			        os.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值