TCP通信程序练习5——上传文件-服务器给出反馈

技术图片

客户端代码:

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //创建客户端Socket对象
        Socket s = new Socket("192.168.50.76", 33333);

        //封装文本文件的数据
        BufferedReader br = new BufferedReader(new FileReader("myNet\\InetAddressDemo.java"));

        //封装输出流写数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        //使输出终止
        //public void shutdownOutput() 禁用此套接字的输出流。
        s.shutdownOutput();

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

        //释放资源
        s.close();
        bw.close();
    }
}

服务器端代码:

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //创建服务器端Socket对象
        ServerSocket ss = new ServerSocket(33333);

        //监听客户端连接
        Socket s = ss.accept();

        //接收数据
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

        //把数据写入文本
        BufferedWriter bw = new BufferedWriter(new FileWriter("myNet\\Copy.java"));
        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();

        //释放资源
        ss.close();
        bw.close();
    }
}

运行结果:

技术图片

技术图片

TCP通信程序练习5——上传文件-服务器给出反馈

原文地址:https://www.cnblogs.com/pxy-1999/p/12869110.html