Server sends data to the client, but the client does not receive

problem:

When sending data to the client through the Socket, the service, the client has been receiving less than

Server sends the code:

ClientWriteHandler.this.printStream.print(msg);

the reason:

When using the print method in code socket, to send data out must add "\ n" newline after the identifying data to be transmitted and the flush () method.

 

printwriter If you enable automatic refresh, then only when a method in which the call println, printf, or format may do this, and not just when output whenever a newline completed. These methods use the platform's own notion of line separator rather than the newline character. 
Further, in a println, has been called flush () method, the source code is as follows:

public void println() {
    newLine();
}
private void newLine() {
    try {
       synchronized (lock) {
        ensureOpen();
        out.write(lineSeparator);
        if (autoFlush)//这里就调用了flush()方法
           out.flush();
       }
    }catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
    }catch (IOException x) {
       trouble = true;
    }
}


In the print is not, the source code is as follows:

public void print(String s) {
    if (s == null) {
       s = "null";
    }
    write(s);
    }
}

Solution:

1, the data using the print () method in the transmission line feed "\ n" and the flush () method

  ClientWriteHandler.this.printStream.print(msg+"\n");
  ClientWriteHandler.this.printStream.flush();

2, a direct call println () method

 ClientWriteHandler.this.printStream.println(msg);

Published 174 original articles · won praise 115 · views 830 000 +

Guess you like

Origin blog.csdn.net/nicolelili1/article/details/103977793