声明
该系列文章由书籍《Netty权威指南》第二版整理而来。只为记录学习笔记。
若认为内容侵权请及时通知本人删除相关内容。
[TOC]
时间服务器--传统的BIO
服务端代码
public class TimeServer {
public static void main(String[] args) throws IOException {
int port = 1234;
ServerSocket server = null;
try {
server = new ServerSocket(port);
System.out.println("The time server is listening in port : " + port);
Socket socket = null;
while (true) {
socket = server.accept();
new Thread(new TimeServerHandler(socket)).start();
}
} finally {
if (server != null) {
System.out.println("The time server close");
server.close();
server = null;
}
}
}
}
public class TimeServerHandler implements Runnable {
private Socket socket;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public TimeServerHandler(Socket socket) {
this.socket = socket;
}
@Override
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 body = null;
while (true) {
body = in.readLine();
if (body == null)
break;
out.println(this.sdf.format(new Date()));
}
} 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();
}
}
}
}
}
客户端代码
public class TimeClient {
public static void main(String[] args) {
int port = 1234;
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.println("time:" + resp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
}
}
}
总结
这种传统的BIO模型有如下特点:
- 新的客户端连接,服务端就要开启一个线程处理--服务器的资源开销不可控
- 无法避免线程频繁创建/销毁的开销
- 客户端连接数量太大很容易导致服务器奔溃
参考资料: 《Netty权威指南》第二版
网友评论