ServerSocket read file stream in java is not read by branch line

learning TCP communication of socket

 TCP 
1.    
2.  

the code is as follows

package com.fuge.TCP.demo2;

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

public class UploadClient {

    public static void main(String[] args) throws IOException {

        //1. tcpsocket
        Socket socket = new Socket("127.0.0.1", 6060);

        //2. 
        BufferedReader bufr = new BufferedReader(new FileReader("D://test.txt"));

        //3. TCP
        //  
        PrintWriter out = new PrintWriter(socket.getOutputStream(),true);

        String line;
        // TCP
        while ((line = bufr.readLine()) != null) {
            out.write(line);
            /**
            *   
            */
            out.flush();   
        }

        // 
       socket.shutdownOutput();

        // 
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String returnMsg = in.readLine();
        System.out.println(returnMsg);

        //
        bufr.close();
        socket.close();

    }

}
package com.fuge.TCP.demo2;

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

public class UploadServer {

    public static void main(String[] args) throws IOException {

        // 1. TCP
        ServerSocket ss = new ServerSocket(6060);

        // socket
        Socket s = ss.accept();

        System.out.println(s.getInetAddress().getHostAddress() + "............connection");

        // 
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        //   D
        BufferedWriter bw = new BufferedWriter(new FileWriter("D://new.txt"));

        String line;
        while ((line = in.readLine()) != null) {
            bw.write(line);
            /**
            * 
            * debug  line  
            */
            bw.newLine();
            bw.flush();
        }
        //   
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        out.write("");
        out.flush();   //   


        //
        bw.close();
        s.close();
        ss.close();

    }

}
May.14,2022

The

first flush method does not guarantee that byte streams are written to the physical network or to the physical disk, but to the operating system's buffer. This can be seen in the API of the flush method. Secondly, what you use here is Socket , and the flush method will write the byte stream to the Socket send buffer. In order to reduce the consumption of network resources, the operating system will send the content of your flush multiple times as a group of messages, so you only need to receive it once on the server side.

as for autoFlush , just take a look at API . It only works after calling println () , printf () , format () methods, while write () is invalid.


client: out.write (line);-> out.println (line);

Menu