What does 'end of stream' mean when working with sockets

前端 未结 4 1513
挽巷
挽巷 2021-02-01 19:52

When working with Sockets in Java, how can you tell whether the client has finished sending all (binary) data, before you could start processing them. Consider for example:

4条回答
  •  Happy的楠姐
    2021-02-01 20:15

    As some ppl already said you can't avoid some kind of protocol for communication. It should look like this for example:

    On the server side you have:

     void sendMSG(PrintWriter out){
        try {
            //just for example..
            Process p = Runtime.getRuntime().exec("cmd /c dir C:");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
    
            //and then send all this crap to the client
            String s = "";
            while ((s = br.readLine()) != null) {
              out.println("MSG");
              out.println(s);
            }
          } catch (Exception e) {
            System.out.println("Command incorrect!");
          }
          out.println("END");
    }
    //You are not supposed to close the stream or the socket, because you might want to send smth else later..
    

    On the client side you have:

    void recieveMSG(BufferedReader in) {
        try {
          while (in.readLine().equals("MSG")) {
            System.out.println(in.readLine());
          }
        } catch (IOException e) {
          System.out.println("Connection closed!");
        }
      }
    

提交回复
热议问题