Java网络编程 TCP网络通信编程文件传输 meowrain 收录于 网络编程2024-05-23 约 300 字 预计阅读 1 分钟 目录 TCP网络通信编程-文件传输 注意 本文最后更新于 2024-05-23,文中内容可能已过时。 TCP网络通信编程-文件传输 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package org.example.socket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TcpServerCopy { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("等待客户端连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端连接成功"); /* 读入文件 */ File file = new File("src/org/example/111658775_p0.png"); FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); /*输出流,向客户端发送文件*/ OutputStream outputStream = socket.getOutputStream(); byte[] buf = new byte[1024]; int bytesRead; while((bytesRead = bufferedInputStream.read(buf))!=-1){ outputStream.write(buf,0,bytesRead); } socket.shutdownOutput(); System.out.println("文件发送完成"); bufferedInputStream.close(); outputStream.close(); socket.close(); serverSocket.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package org.example.socket; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class TcpClientCopy { public static void main(String[] args) throws IOException { Socket socket = new Socket(InetAddress.getLocalHost(),8888); System.out.println("服务器连接成功"); //接受文件内容 InputStream inputStream = socket.getInputStream(); File file = new File("src/client/client.png"); FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); byte[] buf = new byte[1024]; int bytesRead; while((bytesRead = inputStream.read(buf))!=-1){ bufferedOutputStream.write(buf,0,bytesRead); } System.out.println("文件接受成功!"); socket.shutdownInput(); /*关闭资源*/ inputStream.close(); bufferedOutputStream.close(); socket.close(); } } 相关内容 Java网络编程 TCP网络通信编程字符流 Java网络编程 TCP网络通信编程字节流 Go网络编程 JDBC_韩顺平老师转载 Java面向对象基础(高级)