聲明
該系列文章由書籍《Netty權(quán)威指南》第二版整理而來(lái)麦备。只為記錄學(xué)習(xí)筆記怖亭。
若認(rèn)為內(nèi)容侵權(quán)請(qǐng)及時(shí)通知本人刪除相關(guān)內(nèi)容。
[TOC]
時(shí)間服務(wù)器--傳統(tǒng)的BIO
服務(wù)端代碼
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;
}
}
}
}
總結(jié)
這種傳統(tǒng)的BIO模型有如下特點(diǎn):
- 新的客戶端連接积仗,服務(wù)端就要開啟一個(gè)線程處理--服務(wù)器的資源開銷不可控
- 無(wú)法避免線程頻繁創(chuàng)建/銷毀的開銷
- 客戶端連接數(shù)量太大很容易導(dǎo)致服務(wù)器奔潰
參考資料: 《Netty權(quán)威指南》第二版