最近做练习的时候遇到上传文件可以上传成功,但是上传文件之后返回反馈的时候,总是不能成功返回反馈,添加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相当于给文件加一结束标志为。