【图片】
【思路解析】
【客户端代码】
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;/*** @ProjectName: Study* @FileName: TCPFileUploadClient* @author:HWJ* @Data: 2023/7/29 18:44*/
public class TCPFileUploadClient {public static void main(String[] args) throws IOException {Socket socket = new Socket(InetAddress.getLocalHost(), 8888);System.out.println("连接成功...");// 这里采用边从数据通道中读取文件信息,边往新文件中写入数据的操作String filePath = "e:\\qie.png";BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));byte[] bytes = new byte[1024];int readSize = 0;BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());while ((readSize = bufferedInputStream.read(bytes)) != -1) {outputStream.write(bytes, 0, readSize);}outputStream.flush();socket.shutdownOutput();// 这里使用字符流读入BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));String s = reader.readLine(); // 因为使用了writer.newLine来作为结束标记,所以这里一定要使用readLine来读取System.out.println(s);// 一定要关闭所有流对象和网络对象reader.close();bufferedInputStream.close();socket.close();outputStream.close();System.out.println("客户端退出...");}
}
【服务端代码】
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;/*** @ProjectName: Study* @FileName: TCPFileUploadServer* @author:HWJ* @Data: 2023/7/29 18:44*/
public class TCPFileUploadServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket( 8888);System.out.println("服务端,在端口8888,等待连接...");// 等待连接Socket socket = serverSocket.accept();// 这里采用边读取文件信息边往数据通道写入信息的操作String newFile = "src\\new.png";BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFile));BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());byte[] bytes = new byte[1024];int readSize = 0;while ((readSize = inputStream.read(bytes)) != -1){outputStream.write(bytes, 0, readSize);}// 这里发送的是汉字,所以采用字符流传输BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));bufferedWriter.write("成功收到图片");bufferedWriter.newLine();bufferedWriter.flush(); // 这里一定要使用flush刷新,来确保数据被写入到数据通道中// 一定要关闭所有流对象和网络对象outputStream.close();bufferedWriter.close();inputStream.close();serverSocket.close();socket.close();System.out.println("服务端退出...");}
}
【结果展示】