Deprecated: Required parameter $cat_id follows optional parameter $type in /www/wwwroot/ebimall.com/systems/hong.php on line 2088

Deprecated: Required parameter $where follows optional parameter $tree_id in /www/wwwroot/ebimall.com/systems/hlb.php on line 3505
手写Tomcat系列之BIO_HelloWorld的博客-CSDN博客188bio精品生物—专注于实验室精品爆款的电商平台 - 蚂蚁淘旗下精选188款生物医学科研用品
您好,欢迎您进入188进口试剂采购网网站! 服务热线:4000-520-616
蚂蚁淘商城 | 现货促销 | 科研狗 | 生物在线

手写Tomcat系列之BIO_HelloWorld的博客-CSDN博客

目标

理解什么是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(); } } }

 

\"\" \"\" \"\" 点赞 \"\" \"\" 评论

新闻动态
行业前沿
技术文章
最新产品

188进口试剂采购网 www.188bio.cn -中国试剂网,试剂网,化学试剂网,国药试剂,抗体公司,试剂公司,试剂盒公司,苏州试剂公司,北京化学试剂公司,天津化学试剂,试剂商城,试剂代理,流式抗体 细胞库查询 sitemap