- Public class Client {
- public static void Main (String args[]) throws Exception {
- //For the sake of simplicity, all exceptions are thrown directly out
- String host = "127.0.0.1"; //server IP address to connect to
- int port = 8899; //Listening port for the server to be connected
- //Establish a connection with the server
- Socket client = new socket (host, port);
- //Set up a connection to write data to the server
- Writer writer = New OutputStreamWriter (Client.getoutputstream ());
- Writer.write ("Hello Server.");
- Writer.flush (); Remember to flush after you finish writing .
- Writer.close ();
- Client.close ();
- }
- }
For the client to the socket output stream inside the write data to the server to note that if the program is not corresponding to the output stream shutdown, but other blocking operations (such as reading from the input stream), remember to flush, only so that the server can receive the data sent by the client , otherwise it may cause infinite waiting on both sides. I'll talk about it later when I read and write to both the client and the server.
BufferedReader's ReadLine method is to read one line at a time, this method is blocked, until it reads a line of data so that the program will continue to execute, then when will readline read a line? Until the program encounters a newline character or the Terminator ReadLine method of the corresponding stream, it will think that it has read a line before it ends its blocking and the program continues to execute. So when we use the BufferedReader readline to read the data, we must remember that in the corresponding output stream must write a newline character (after the end of the stream is automatically marked as the end, ReadLine can be recognized), After writing a newline character, remember to flush the output stream if it is not closed immediately, so that the data is actually written from the buffer.
Socket IO Remember flush