硅谷某神的视频实例3中不用socket.shutdownOutput()服务端就会被阻塞,但是实例1和实例2也没用为啥没阻塞呢?
找了半天才理解原来
socket.shutdownOutput();作用:关闭数据的输出 //给服务端发送一个说完了信号,否则对方的读取方法会一致阻塞,会在流末尾写入一个“流的末尾”标记,对方才能读到-1
实例3需要是因为需要接收服务端返回消息,客户端socket.shutdownOutput()让服务端while终止读取,接着走下面返回消息给客户端代码
实例1 2不需要是因为 不需要接收服务端返回消息 直接socket.close()了 socket.close()也是给服务端一个终止信息
下面代码没用ry-catch-finally处理异常请忽略
客户端发送文件给服务端,服务端将文件保存在本地
@Test
public void client() throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
fis.close();
os.close();
socket.close();
}
public void server() throws IOException {
ServerSocket ss = new ServerSocket(9090);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
socket.close();
ss.close();
}
}
6.5 示例三:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。
@Test
public void client() throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
**//关闭数据的输出 //给服务端发送一个说完了信号,否则对方的读取方法会一致阻塞,会在流末尾写入一个“流的末尾”标记,对方才能读到-1
**socket.shutdownOutput();**
//上面不需要是因为 不需要步骤5 接收服务端消息 直接socket.close()了 socket.close()也是给服务端一个终止信息。**
//5.接收来自于服务器端的数据,并显示到控制台上
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bufferr = new byte[20];
int len1;
while((len1 = is.read(buffer)) != -1){
baos.write(buffer,0,len1);
}
System.out.println(baos.toString());
fis.close();
os.close();
socket.close();
baos.close();
}
@Test
public void server() throws IOException {
ServerSocket ss = new ServerSocket(9090);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
System.out.println("图片传输完成");
OutputStream os = socket.getOutputStream();
os.write("你好,美女,照片我已收到,非常漂亮!".getBytes());
fos.close();
is.close();
socket.close();
ss.close();
os.close();
}
}