Socket实战——文件下载

11 篇文章 0 订阅

Socket实战系列:
Socket实战——UDP连接:https://blog.csdn.net/haoranhaoshi/article/details/86601468
Socket实战——TCP连接:https://blog.csdn.net/haoranhaoshi/article/details/86601522
Socket实战——查询数据库:https://blog.csdn.net/haoranhaoshi/article/details/86601566
Socket实战——监听数据库:https://blog.csdn.net/haoranhaoshi/article/details/86601584
Socket实战——聊天:https://blog.csdn.net/haoranhaoshi/article/details/86601771
Socket实战——文件上传:https://blog.csdn.net/haoranhaoshi/article/details/86601850
Socket实战——文件下载:https://blog.csdn.net/haoranhaoshi/article/details/86632897

项目下载地址(IDEA搭建):https://download.csdn.net/download/haoranhaoshi/10933044

客户端与服务端建立TCP的Socket连接,服务端得到客户端的发送的想下载的文件名,将文件反馈发送给客户端。

package FileDownloadByTCP;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端与服务端建立TCP的Socket连接,服务端得到客户端的发送的想下载的文件名,将文件反馈发送给客户端
 */
public class FileDownloadServer extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("等待客户端发送!");
        try {
            // 端口:1024-65535
            ServerSocket serverSocket = new ServerSocket(10086, 50, InetAddress.getByName("127.0.0.1"));
            new Thread(() -> {
                try {
                    Socket socket;
                    // 等待客户端的连接
                    while (true) {
                        // 服务端接收
                        socket = serverSocket.accept();
                        // 未收到则后续不执行
                        String message = "";
                        InputStream inputStream = socket.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String lineMessage;
                        while ((lineMessage = bufferedReader.readLine()) != null) {
                            message += lineMessage;
                        }

                        String finalMessage = message;
                        Platform.runLater(() -> label.setText("下载" + finalMessage));
                        // 关闭输入流
                        socket.shutdownInput();
                        // 服务端往客户端发送
                        OutputStream outputStream = socket.getOutputStream();
                        FileInputStream fileInputStream = new FileInputStream(new File("").getAbsolutePath() + "/src/FileDownloadByTCP/" + message);
                        byte[] bytes = new byte[1024];
                        int length;
                        while((length = fileInputStream.read(bytes))!=-1){
                            outputStream.write(bytes,0,length);
                        }
                        // 关闭输出流,才能发送,outputStream.close()、printWriter.close()、socket.close()可发送但会关闭连接,
                        // socket.shutdownOutput()不关闭连接,但四种方式都不能再socket.getOutputStream(),前三种报Socket is closed异常,
                        // 最后一种报Socket is shut down
                        socket.shutdownOutput();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        primaryStage.setTitle("FileDownloadServer");
        Pane pane = new Pane(label);
        primaryStage.setScene(new Scene(pane, 400, 200));
        primaryStage.setX(100);
        primaryStage.setY(100);
        primaryStage.show();

        primaryStage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, event -> {
            Platform.exit();
            System.exit(0);
        });
    }
}
package FileDownloadByTCP;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class FileDownloadClient extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("等待服务端回复!");
        label.setTranslateY(50);
        Button button = new Button("下载");

        button.setOnAction(event -> {
            try {
                // 客户端向服务端发送
                Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 10086);
                OutputStream outputStream = socket.getOutputStream();

                byte[] bytes = "test1.txt".getBytes();
                outputStream.write(bytes,0,bytes.length);
                socket.shutdownOutput();

                new Thread(() -> {
                    while (true) {
                        // 客户端接收服务端的反馈
                        InputStream inputStream;
                        try {
                            inputStream = socket.getInputStream();
                            if (inputStream.available() == 0) {
                                continue;
                            }

                            String fileName = "test2.txt";
                            File file = new File(new File("").getAbsolutePath() + "/src/FileDownloadByTCP/" + fileName);
                            if(file.exists()){
                                file.delete();
                            }

                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                            byte[] fileBytes = new byte[1024];
                            int length;
                            while((length = inputStream.read(fileBytes)) != -1){
                                fileOutputStream.write(fileBytes, 0, length);
                            }

                            Platform.runLater(() -> label.setText("已下载,保存为:" + fileName));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        primaryStage.setTitle("FileDownloadClient");
        Pane pane = new Pane(label, button);
        primaryStage.setScene(new Scene(pane, 400, 200));
        primaryStage.setX(500);
        primaryStage.setY(100);
        primaryStage.show();

        primaryStage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, event -> {
            Platform.exit();
            System.exit(0);
        });
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风铃峰顶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值