NIO入门之BIO
传统BIO编程
网络编程的基本模型是Client-Server模型,也就是两个进程之间相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的端口发起连接请求,通过三次握手建立连接,如果连接成功,双方就可以通过网络套接字(Socket)进行通信。
在传统的BIO编程中,ServerSocket负责绑定IP地址,启动端口监听,Socket负责发起连接请求,连接成功之后,双方通过输入和输出流进行同步阻塞通信。
下面通过TimeServer的一个例子,回顾和熟悉BIO编程
BIO通信模型图

可以看到再改模型中,有一个Acceptor线程负责监听客户端的连接,并为每个请求创建一个新的线程进行处理。
我们可以发现该模型最大问题就是缺乏弹性伸缩能力,服务端和客户端线程个数是1比1的关系。
BIO的TimeServer
package nio.bio;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by jj on 2018/12/23.
*/
public class TimeServer {
public static void main(String[] args) throws IOException {
int port = 8080;
if (args != null && args.length >0){
try{
port = Integer.parseInt(args[0]);
}catch (NumberFormatException e){
}
}
ServerSocket server = null;
try{
server = new ServerSocket(port);
Socket socket = null;
while (true){
socket = server.accept();
new Thread(new TimeServerHandler(socket)).start();
}
}finally {
if (server!= null){
server.close();
server = null;
}
}
}
}
如果没有客户端请求,则阻塞在server.accept操作上,如果有,则创建一个TimeServerHandler的Runnable线程,处理客户端的Socket链路
下面,我们看一下TimeServerHandler
public class TimeServerHandler implements Runnable{
private Socket socket;
public TimeServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(),true);
String curentTime = null;
String body = null;
while (true){
body = in.readLine();
if (body == null)
break;
System.out.println("the time server receive order:" + body);
curentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(
System.currentTimeMillis()
).toString():"BAD ORDER";
out.println(curentTime);
}
} catch (Exception e) {
if (in != null){
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null){
out.close();
out = null;
}
if (this.socket !=null){
try {
this.socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
this.socket = null;
}
}
}
}
可以看到run中的功能为读取客户端请求,并通过PrintWriter返回给客户端相应。
下面我们看一下客户端的代码
public class TimeClient {
public static void main(String[] args) throws IOException {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
}
}
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try{
socket = new Socket("127.0.0.1",port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
out.println("QUERY TIME ORDER");
String resp = in.readLine();
System.out.print(resp);
}finally {
if (out != null){
out.close();
out = null;
}
if (in != null){
in.close();
in = null;
}
if (socket != null){
socket.close();
socket = null;
}
}
}
}
NIO入门之BIO的更多相关文章
- 第二章 NIO入门
传统的同步阻塞式I/O编程 基于NIO的非阻塞编程 基于NIO2.0的异步非阻塞(AIO)编程 为什么要使用NIO编程 为什么选择Netty 第二章 NIO 入门 2.1 传统的BIO编程 2.1.1 ...
- Java NIO入门(二):缓冲区内部细节
Java NIO 入门(二)缓冲区内部细节 概述 本文将介绍 NIO 中两个重要的缓冲区组件:状态变量和访问方法 (accessor). 状态变量是前一文中提到的"内部统计机制"的 ...
- Java NIO入门
NIO入门 前段时间在公司里处理一些大的数据,并对其进行分词.提取关键字等.虽说任务基本完成了(效果也不是特别好),对于Java还没入门的我来说前前后后花了2周的时间,我自己也是醉了.当然也有涉及到机 ...
- NIO入门之轻松读取大文件
NIO入门之轻松读取大文件 今天同事碰到了一个问题,从游戏服务器下载下来的输出log有一个多G大.用记事本打不开,EditPlus也打不开,都提示文件太大.用word也打不开,提示文件大于512M.打 ...
- NIO 入门(转)
NIO 入门 Greg Travis2003 年 11 月 17 日发布 分享此页面 WeiboGoogle+用电子邮件发送本页面 20 在开始之前 关于本教程 新的输入/输出 (NIO) 库是在 J ...
- NIO入门-----01
package com.sico.pck01_nio; import java.nio.ByteBuffer; import org.junit.Test; /** * @author Sico ...
- 史上最强Java NIO入门:担心从入门到放弃的,请读这篇!
本文原题“<NIO 入门>,作者为“Gregory M. Travis”,他是<JDK 1.4 Tutorial>等书籍的作者. 1.引言 Java NIO是Java 1.4版 ...
- 从Socket入门到BIO,NIO,multiplexing,AIO
Socket入门 最简单的Server端读取Client端内容的demo public class Server { public static void main(String [] args) t ...
- 从Socket入门到BIO,PIO,NIO,multiplexing,AIO(未完待续)
Socket入门 最简单的Server端读取Client端内容的demo public class Server { public static void main(String [] args) t ...
随机推荐
- ASP.net MVC入门及Razor语法
一.MVC入门: 1.MVC简介 约定大于配置 2.MVC访问流程 csthml模板(razor模板)就是简化HTML的拼接的模板,最终还是生成html给浏览器显示,不能直接访问cshtml文件. 二 ...
- ironic state information
参考: http://blog.csdn.net/zhonglinzhang/article/details/74202562 http://blog.csdn.net/wanghuiict/arti ...
- go语言的学习网站
1)http://www.runoob.com/go/go-data-types.html 2)https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/ ...
- Linux查看端口被占用情形
查看某端口的占用情况: lsof -i:<端口号> 例如:lsof -i:8080 netstat -apn|grep <端口号> 例如: netstat -apn | gre ...
- HDU 4455 Substrings ( DP好题 )
这个……真心看不出来是个DP,我在树状数组的康庄大道上欢快的奔跑了一下午……看了题解才发现错的有多离谱. 参考:http://www.cnblogs.com/kuangbin/archive/2012 ...
- 软工实践 - 第十六次作业 Alpha 冲刺 (7/10)
队名:起床一起肝活队 组长博客:https://www.cnblogs.com/dawnduck/p/10013959.html 作业博客:班级博客本次作业的链接 组员情况 组员1(队长):白晨曦 过 ...
- ocrosoft Contest1316 - 信奥编程之路~~~~~第三关 问题 x: 十进制到二进制的转换
http://acm.ocrosoft.com/problem.php?cid=1316&pid=49 题目描述 把十进制到二进制的转换. 输入 234 输出 11101010 样例输入 23 ...
- [C语言]防止头文件和全局变量重复定义
昨天下午将全局变量定义在H文件中导致链接时提示变量在多个obj文件内重复. 解决办法如下: 将变量移入C文件中进行定义,然后在H文件中加入extern在变量之前. 这样当其它C文件引用该全局变量时 ...
- HDU1520 树形DP入门
Anniversary party Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- Create Windows Server 2008 cluster from the command line
How to create a Windows Server 2008 cluster from the command line? Creating a cluster in Server 2008 ...