【Java】TCP从客户端上传文件保存到服务端并给出反馈(多线程改进版)

客户端

package LearnJava17.Tcptx4;

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

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        Socket s=new Socket("127.0.0.1",10000);
        BufferedReader br=new BufferedReader(new FileReader("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx3\\test.txt"));
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        String line;
        while ((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

//        自定义结束标记
//        bw.write("886");
//        bw.newLine();
//        bw.flush();

//        标准结束标记
        s.shutdownOutput();

//        接收反馈
        BufferedReader brClient=new BufferedReader(new InputStreamReader(s.getInputStream()));
        String data = brClient.readLine();
        System.out.println("服务器反馈:"+data);

        s.close();
        br.close();
    }
}

服务端

package LearnJava17.Tcptx4;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(10000);
        while (true){
            Socket s = ss.accept();
            new Thread(new ServerThread(s)).start();
        }
    }
}

多线程

package LearnJava17.Tcptx4;

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

public class ServerThread implements Runnable{
    private Socket s;
    public ServerThread(Socket s) {
        this.s=s;
    }

    @Override
    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//            BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx4\\test2.txt"));
//            解决名称问题
            int count=0;
            File file=new File("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx4\\test("+count+").txt");
            while (file.exists()){
                count++;
                file=new File("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx4\\test("+count+").txt");
            }
            BufferedWriter bw=new BufferedWriter(new FileWriter(file));

            String line;
            while ((line=br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            //      给出反馈
            BufferedWriter bwServer =new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bwServer.write("文件上传成功!");
            bwServer.newLine();
            bwServer.flush();
            s.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

posted @ 2022-04-30 17:31  木子欢儿  阅读(27)  评论(0编辑  收藏  举报