Java通过TCP协议实现文件的上传
需求:1、从客户端将文件上传到服务器
2、服务器接收完成,需要反馈到客户端
-
客户端代码
package advanced.day12.demo03; import java.io.*; import java.net.Socket; /** * @author Object(object_hui@sina.com) * @description 客户端类,上传文件到服务器 * @date 2020/9/16 */ public class Client { public static void main(String[] args) throws IOException { //创建一个socket连接,模拟使用本地IP地址 Socket socket = new Socket("127.0.0.1", 9527); //创建一个输入流和一个输出流 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\typora\\thema\\test.txt"))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); //读取文件数据,文件不为空时,上传文件内容到服务器 String line; while ((line = br.readLine())!=null) { bw.write(line); bw.newLine(); bw.flush(); } //关闭输出流,告诉服务器已经传输完毕 socket.shutdownOutput(); //创建一个输入流,去socket中读取服务器反馈信息 BufferedReader brClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); String info = brClient.readLine(); System.out.println("收到服务器消息:"+info); //关闭socket和流 brClient.close(); socket.close(); br.close(); bw.close(); } }
-
服务端代码
package advanced.day12.demo03; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author Object(object_hui@sina.com) * @description 服务器类,接收文件,并给客户端反馈 * @date 2020/9/16 */ public class Server { public static void main(String[] args) throws IOException { //创建一个ServerSocket连接 ServerSocket serverSocket = new ServerSocket(9527); //获取一个socket对象 Socket socket = serverSocket.accept(); //创建一个输入流 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //创建一个输出流,将获取到的输入内容放到指定的位置 BufferedWriter bw = new BufferedWriter(new FileWriter("./text.txt")); //当读取到的数据不为空,写入目标文件 String line; while ((line = br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //创建一个输出流,写点东西反馈到客户端 BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bwServer.write("文件接收完毕"); bwServer.newLine(); bwServer.flush(); //对socket连接和流进行关闭操作 bwServer.close(); serverSocket.close(); br.close(); bw.close(); } }