Java IO网络编程为什么这里没有阻塞
本帖最后由 Aojacy 于 2019-9-23 22:58 编辑package netStream;
import org.junit.Test;
import java.io.*;
import java.net.*;
public class SocketTest2 {
@Test
public void clientTest(){
Socket socket = null;
OutputStream os = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("hello1.jpg"));
byte[] buff = new byte;
int len;
while ((len = fis.read(buff))!=-1){
os.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void serveTest() throws IOException {
ServerSocket serverSocket = null;
Socket acceptSocket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
serverSocket = new ServerSocket(9090);
acceptSocket = serverSocket.accept();
is = acceptSocket.getInputStream();
fos = new FileOutputStream(new File("hello2.jpg"));
byte[] buff = new byte;
int len;
while ((len = is.read(buff))!=-1){
fos.write(buff,0,len);
}
System.out.println("复制成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos!=null){
fos.close();
}
if(is!=null){
is.close();
}
if(acceptSocket!=null){
acceptSocket.close();
}
if(serverSocket!=null){
serverSocket.close();
}
}
}
}
按理说第57行不会执行到,上面循环会进入阻塞,为什么实际没有阻塞? 自己想通了,后面紧跟着有个close(),应该和socket.shutdownOutput()作用差不多,可以让服务器接收到文件结束标记
页:
[1]