输入输出流的shutdownoutput和shutdowninput方法的使用(文件默认有一个-1的结束标志位)

最近做练习的时候遇到上传文件可以上传成功,但是上传文件之后返回反馈的时候,总是不能成功返回反馈,添加shutdownoutput就可以了,

练习如下:

server端代码:

public class server {
	public static void main(String[] args) throws IOException {
		ServerSocket ss=new ServerSocket(8802);
		Socket a = ss.accept();
		InputStream in = a.getInputStream();
		FileOutputStream fos=new FileOutputStream("e.jpg");
		int len=-1;
		byte[] b=new byte[1024];
		while((len=in.read(b))!=-1){
			fos.write(b, 0, len);
		}
		
		//-----------------------反馈信息----------------------------------
		
		OutputStream out = a.getOutputStream();
		out.write("我已经接收到图片了".getBytes());
		
		out.close();
		fos.close();
		in.close();
		ss.close();
	}
}

client端代码:

public class client {
	public static void main(String[] args) throws IOException {
		Socket so=new Socket(InetAddress.getLocalHost(), 8802);
		OutputStream out = so.getOutputStream();
		FileInputStream fis=new FileInputStream("D:\\a.jpg");
		int len=-1;
		byte[] b=new byte[1024];
		while((len=fis.read(b))!=-1){
			out.write(b,0,len);
		}
		so.shutdownOutput();
		//------------收到反馈信息----------
		InputStream in = so.getInputStream();
		
		int length=in.read(b);
		System.out.println(new String(b,0,length));
		
		fis.close();
		out.close();
		so.close();
	}
}

服务器端代码接收数据的时候是:

服务器端代码读取的时候源代码如下:

 public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
b不等于空,也不符合第二条情况,但是读取的长度是0,所以是第三种情况,因此会返回0.如果服务器端不加shutdownoutput的话,相当于不加结束标志位,然后服务器端读取到结尾的时候读不到文件结束标志位,然后会一直循环下去,每次读0个字节写0个字节。shutdownoutput相当于给文件加一结束标志为。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值