服务端:
监听端口,监听客户端发送的消息,返回服务器时间给客户端。
package com.tech.netty.bio;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lw
* @since 2021/9/13
*/
public class BioServer {
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("the time server is start in port :" + PORT);
Socket socket = null;
while (true) {
socket = serverSocket.accept();
new Thread(new TimeServerHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
System.out.println("the time server close");
serverSocket.close();
}
}
}
}
package com.tech.netty.bio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
/**
* @author lw
* @since 2021/9/13
*/
public class TimeServerHandler implements Runnable {
private Socket socket;
public TimeServerHandler(Socket socket) {
this.socket=socket;
}
@Override
public void run() {
BufferedReader in=null;
PrintWriter out=null;
try{
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new PrintWriter(socket.getOutputStream(),true);
String body;
while((body=in.readLine())!=null && body.length()!=0){
System.out.println("the time server receive msg :"+body);
out.println(new Date().toString());
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(this.socket!=null){
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端:
连接服务器,发送消息给服务器,打印服务器返回的消息。
package com.tech.netty.bio;
import java.io.*;
import java.net.Socket;
/**
* @author lw
* @since 2021/9/13
*/
public class BioClient {
private static final String HOST = "127.0.0.1";
private static final int PORT = 8080;
public static void main(String[] args) {
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socket = new Socket(HOST, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
out.println("i am client");
String resp = in.readLine();
System.out.println("当前服务器时间是:" + resp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
特点分析:
? ? ? ? 优点:模型和编程简单。
? ? ? ? 缺点:一个线程处理一个连接,在高并发场景下,CPU切换线程上下文资源消耗大。
? ? ? ? tomcat7之前的版本采用BIO,之后的版本采用NIO。
? ? ? ? 可以使用线程池,改进BIO。
|