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 来进行服务端和客户端的网络通信。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值