目录
1.通过java编写BIO client——service(scocket)通信
1.通过java编写BIO client——service(scocket)通信
(1)创建一个java工程
(2)编写socket服务端的骨架
accept方法会进行堵塞,收到一个连接就会开启一个线程进行处理。
TimeServerHandler类进行客户的处理。所以要接收socket对象
注:(每一个连接进来就需要一个handler来处理)处理对应的业务逻辑都以handle结尾
(3)编写Handler
(4)测试
public class BioServer {
private static final int PORT = 8080;
public static void main(String[] args)throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(PORT);
System.out.println("the time server is start in port :"+PORT);
Socket socket = null;
while (true){
socket = server.accept();
new Thread(new TimeServerHandler(socket)).start();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(server != null){
System.out.println("the time server close");
server.close();
}
}
}
}
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(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(),true);
String body = null;
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 (Exception e){
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(this.socket != null){
try{
this.socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
2.编写客户端
(1)通过创建socket确定主机和端口号
(2)操作输入输出的io流
(3)测试
public class BioClientor {
private static final int PORT=8080;
private static final String HOST="127.0.0.1";
public static void main(String[] args){
Socket socket=null;
// BufferedReader
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("我是客户端"+1111111111);
String res = in.readLine();
System.out.println("获取的服务端的时间为:"+res);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (socket!=null)
try{
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
out.close();
}
}
}
}
3.BIO的优缺点的分析及改进
简介:讲解BIO的优缺点,为啥不能高并发情况下性能弱
(1) 优点:
模型简单
编码简单
(2)缺点:
性能瓶颈,请求数和线程数 N:N关系
高并发情况下,CPU切换线程上下文损耗大
案例:web服务器Tomcat7之前,都是使用BIO,7之后就使用NIO
改进:伪NIO,使用线程池去处理业务逻辑