【Java】TCP从客户端上传文件保存到服务端并给出反馈

2022/4/30 17:42:43

本文主要是介绍【Java】TCP从客户端上传文件保存到服务端并给出反馈,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

客户端

package LearnJava17.Tcptx3;

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.Tcptx3;

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

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);
//        监听客户端连接
        Socket s = ss.accept();
//        接收数据
        BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx3\\test2.txt"));
        String line;
        while ((line=br.readLine())!=null){
//            if ("886".equals(line)){
//                break;
//            }
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
//      给出反馈
        BufferedWriter bwServer =new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bwServer.write("文件上传成功!");
        bwServer.newLine();
        bwServer.flush();

        ss.close();
        bw.close();
    }
}



这篇关于【Java】TCP从客户端上传文件保存到服务端并给出反馈的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程