java BIO read阻塞

    技术2026-04-22  15

    TCP流是无界限的,所以会有阻塞,等待发送结束标识-1 server public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8989);

    while(true){ //等待客户端连接,阻塞方法 //Socket数据发送者在服务端的引用 Socket client = server.accept(); System.out.println(client.getPort()); //对方法数据给我了,读 Input InputStream is = client.getInputStream(); //网络客户端把数据发送到网卡,机器所得到的数据读到了JVM内中 byte [] buff = new byte[1024];

    // int len = is.read(buff); int len; while((len=is.read())!=-1){ System.out.println(“收到” + (byte)len); } System.out.println(“server-end” + len); System.out.println(“server-end” ); // if(len > 0){ // String msg = new String(buff,0,len); // System.out.println(“收到” + msg); // } } } client

    public static void main(String[] args) throws IOException, InterruptedException { //要和谁进行通信,服务器IP、服务器的端口 //一台机器的端口号是有限 Socket client = new Socket(“localhost”, 8989);

    //输出 O write(); //不管是客户端还是服务端,都有可能write和read OutputStream os = client.getOutputStream(); //生成一个随机的ID String name ="a";// UUID.randomUUID().toString(); System.out.println("客户端发送数据:" + name); //传说中的101011010 os.write(name.getBytes()); Thread.sleep(10000); System.out.println("sleep:" + 10000); //os.close(); os.flush(); client.shutdownOutput(); client.close();

    总结: 服务端执行到read时候,如果 客户端没有执行os.close();或者 client.shutdownOutput();服务算的read会阻塞状态 os.close();或者 client.shutdownOutput() 作用是让服务端接收到 -1 结束标识

    read(byte[])如下图,read(byte[])里也是调用了read()方法

    Processed: 0.013, SQL: 9