欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Java重修笔记 TCP 网络通信编程 - 传输文件

Java重修笔记 TCP 网络通信编程 - 传输文件

2024/10/23 13:11:11 来源:https://blog.csdn.net/Code___slave/article/details/142984004  浏览:    关键词:Java重修笔记 TCP 网络通信编程 - 传输文件

 1. 服务器端

public class TCPFileCopyServer {public static void main(String[] args) throws Exception {// 服务器端在 8888 端口监听ServerSocket serverSocket = new ServerSocket(8888);// 等待连接System.out.println("服务端在端口 8888 监听....");Socket socket = serverSocket.accept();// 接收客户端传过来的图片InputStream inputStream = socket.getInputStream();BufferedInputStream bis = new BufferedInputStream(inputStream);byte[] bytes = StreamUtils.streamToByteArray(bis);// 设置图片存放路径File file = new File("src\\imageCopy.png");// 设置为追加方式写入FileOutputStream fos = new FileOutputStream(file, true);BufferedOutputStream bos = new BufferedOutputStream(fos);bos.write(bytes);bos.close();socket.shutdownInput();// 向客户端发送信息发送OutputStream outputStream = socket.getOutputStream();OutputStreamWriter osw = new OutputStreamWriter(outputStream);BufferedWriter writer = new BufferedWriter(osw);writer.write("收到图片");writer.flush();// 关闭其他资源writer.close();bis.close();socket.close();serverSocket.close();}
}

2. 客户端

public class TCPFileCopyClient {public static void main(String[] args) throws Exception {// 客户端往端口 8888 发一张图片Socket socket = new Socket(InetAddress.getLocalHost(), 8888);// 设置图片路径String filePath = "d:\\hnt.png";File file = new File(filePath);// 读出图片内容FileInputStream fileInputStream = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(fileInputStream);// 获取文件内容存放到 bytes 数组byte[] bytes = StreamUtils.streamToByteArray(bis);// 发送数据OutputStream outputStream = socket.getOutputStream();BufferedOutputStream bos = new BufferedOutputStream(outputStream);bos.write(bytes); // 写入bis.close(); // 关闭输入流socket.shutdownOutput(); // 设置结束标记// 接收从服务端传来的消息InputStream inputStream = socket.getInputStream();String s = StreamUtils.streamToString(inputStream);System.out.println(s);// 关闭其他资源inputStream.close();bos.close();socket.close();}
}

3. 工具类

public class StreamUtils {public static byte[] streamToByteArray(InputStream is) throws Exception {ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出流对象byte[] b = new byte[1024];//字节数组int len;while ((len = is.read(b)) != -1) {//循环读取bos.write(b, 0, len);//把读取到的数据,写入bos}byte[] array = bos.toByteArray();//然后将bos 转成字节数组bos.close();return array;}public static String streamToString(InputStream is) throws Exception {BufferedReader reader = new BufferedReader(new InputStreamReader(is));StringBuilder builder = new StringBuilder();String line;while ((line = reader.readLine()) != null) {builder.append(line + "\r\n");}return builder.toString();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com