java BIO模型demo

 注意点是BIO是java的传统编程模型,就是java.io包下和java.net包下

是一个客户端和服务端的建立的连接对应一个线程,socket会进行 write()/read()BIO缺点是线程资源的浪费会造成资源开销的浪费

是同步阻塞 会在socket.accept()方法和read()方法进行阻塞

java BIO模型的server端 demo如下:

package com.example.demo.Bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {
    public static void main(String[] args) throws Exception{

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true){
            Socket socket = serverSocket.accept();
            System.out.println("连接到客户端");
            executorService.submit(new Runnable(){
                @Override
                public void run() {
                  handle(socket);
                }
            });
        }

    }

    public static void handle(Socket socket){

        System.out.println("id:"+Thread.currentThread().getId());
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.println("读取客户端数据"+new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }
}

 

client端demo:

public class BioClient {
    public static void main(String[] args) throws Exception {
        Socket client = new Socket("127.0.0.1", 6666);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                handle(client);
            }
        });
        thread.start();
    }
    public static void handle(Socket socket){
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.println("Hello World");
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

 

通过telnet 127.0.0.1 6666 来进行服务端和客户端的网络通信。

 

posted @ 2020-10-09 17:23  彬在俊  阅读(255)  评论(0编辑  收藏  举报