IO的read方法返回-1和阻塞的区别

2017-05-09  本文已影响0人  假鞋子

之前一直在疑惑,什么叫阻塞,什么叫结束。潜意识以为这两个都是服务器读到最后 了
一定程度上来讲是的,都是当前内容读到了最后。但是返回-1是当前流到了最后,而阻塞是因为当前流读到了最后没内容了,但是客户端还没有关闭流。
当客户端关闭了输出流的时候,服务器会知道。返回-1。否则等待接下来的数据或者等待关闭.例子如下
服务端

package com.jiaxz.io.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;

public class Servers {

    public void test() throws IOException{
        ServerSocket ss = new ServerSocket(8888);
        InputStream is = null;
        try {
            is = ss.accept().getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        byte[] data = new byte[8];
        int length;
        while((length = is.read(data)) != -1){
            String result = new String(data);
            System.out.println(result);
            System.out.println("length:" + length);
        }
        System.out.print("success");
    }
    
    public static void main(String[] args) {
        Servers server = new Servers();
        try {
            server.test();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

<br />

客户端

package com.jiaxz.io.test;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public void test() throws UnknownHostException, IOException, InterruptedException{
        String msg = "11";
        byte[] byteMsg = msg.getBytes();

        Socket socket = new Socket("localhost", 8888);
        OutputStream out = socket.getOutputStream();
        BufferedOutputStream bw = new BufferedOutputStream(out);
        for (int i = 0;i<10;i++) {
            bw.write(byteMsg);
            Thread.sleep(2*(2^i));
            bw.flush();
        }
        bw.close();
        for (int i = 0;i<10;i++) {
            bw.write(byteMsg);
            Thread.sleep(2*(2^i));
            bw.flush();
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        try {
            client.test();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

flush()是什么用的?交由下一章节

上一篇下一篇

猜你喜欢

热点阅读