JR
2024-03-30
#提问# socket编程的IO流关闭顺序是什么?这是我的服务端代码和客户端代码,此时可以正常运行。但是将服务端的bis.close();放到bos.close();后面就会报错:Socket is closed。更改客户端的bos.close();的位置也会导致Socket is closed。是服务端和客户端之间的IO流只能在最后一起关闭吗? public class TCPFileUploadServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); String file_path = "tarimg\\2.jpg"; BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file_path)); int readLen = 0; byte[] buf = new byte[1024]; while((readLen = bis.read(buf))!=-1){ bos.write(buf,0,readLen); } bos.flush(); bos.close(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("收到图片"); bw.newLine(); bw.flush(); socket.shutdownOutput(); bw.close(); bis.close(); socket.close(); serverSocket.close(); System.out.println("已发送"); } } public class TCPFileUploadClient { public static void main(String[] args) throws IOException { Socket socket = new Socket(InetAddress.getLocalHost(),9999); String file_path = "srcimg\\1.jpg"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file_path)); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); byte[] buf = new byte[1024]; int readLen = 0; while((readLen = bis.read(buf))!=-1){ bos.write(buf,0,readLen); } bos.flush(); bis.close(); socket.shutdownOutput(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String s = br.readLine(); System.out.println(s); br.close(); bos.close(); socket.close(); } }
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP