如题所示,read进入阻塞状态怎么办 以及为什么会进入阻塞状态,文件为什么读取到末尾不返回-1结束标记。
客户端
import javafx.print.Printer;
import java.io.*;
import java.net.Socket;
import java.util.HashMap;
public class FuXi2 {
public static void main(String[] args) throws IOException {
demo01();
demo02();
}
private static void demo02() throws IOException {
FileInputStream a = new FileInputStream("C:\\Users\\shanyang\\Desktop\\q3w");//创建本地文件输入流
Socket a2 = new Socket("127.0.0.1", 8888);//创建端点指定ip地址和端口号
OutputStream outputStream = a2.getOutputStream();//获取端点传输之间的io流中的outputstream
int q = 0;
byte[] w = new byte[1024];
byte[] w1 = new byte[1024];
while ((q = a.read(w)) != -1) {//一次读取所有文件字节
outputStream.write(w, 0, q);//-1结束标记没有写入 -1写里面有用吗? 下次再read的时候读取到末尾不就自动返回-1了吗?
}//往服务器端输出文件 但没有结束标记、
a2.shutdownOutput();//关闭套接字的输出流 大概意思就是关闭此套接字的输出流,服务器端不用等待然后读到末尾直接返回-1然后就结束了while循环
InputStream a3 = a2.getInputStream();//获取客户端的输入流。接受的是服务器端的输出流输出的内容
while ((q = a3.read(w1)) != -1) {
System.out.println(new String(w1, 0, q));//遍历服务器端输出的内容
}
outputStream.close();
a2.close();
a.close();
}
private static void demo01() {
}
}
服务器端
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FuXi4{
public static void main(String[] args) throws IOException {
ServerSocket a = new ServerSocket(8888);
Socket accept = a.accept();
InputStream inputStream = accept.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\shanyang\\Desktop\\q7w");
int o =0;
byte[] p = new byte[1024];
while((o=inputStream.read(p))!=-1){//注意端点的输入流有特殊情况,就是如果没有读到文件里的-1是不会结束的,也根本读取不到末尾 因为他会一直认为客户端还有没上传完的文件
// System.out.println(new String(p,0,o));
fileOutputStream.write(p,0,o);
}//因为没有读取到-1结束标记所以不确定客户端是否还有内容 所以进入阻塞状态。 因为网络传输几乎是同步的所以不确定是否还有数据要传输进来所以必须要有结束标记-1
// 就算你字节只有5个 后面也不会读取到末尾返回-1结束标记,因为同步的根部不会确定是否还有你后续输入的内容
//或者调用方法关闭这个流返回一个-1.
//
OutputStream outputStream = accept.getOutputStream();//创建端点输出流返回给客服端数据
outputStream.write("谢谢啊".getBytes());
outputStream.close();
fileOutputStream.close();
inputStream.close();
}
}