A recent problem with writing a simple socket example is that the data can be received normally by using the Write.flush () target-side read without receiving the data. This makes me very puzzling, remember when learning the flush method, it is the method is forced to flush the buffer content into the output stream. is the socket output stream different. See a lot of people on the Internet ask this question, explain is also a variety of. Then I finally found the reason, there are so confused compatriots can refer to, the problem is not the logic of output, but Read method. First code:
Service-side Server.java:
try{
serversocket server = new ServerSocket (9090);
while (true) {
Socket socket=server.accept ();
SYSTEM.OUT.PRINTLN ("Receive Client" +socket.getinetaddress () + "connection request");
Reader reader = new InputStreamReader (Socket.getinputstream ());
Char chars[] = new char[64];
int Len;
StringBuilder sb = new StringBuilder ();
while ((Len=reader.read (chars))!=-1) {
sb.append (new String (chars, 0, Len));
System.out.println ("Received information:" +sb.tostring ());
}
catch (IOException e) {
//TODO auto-generated catch block
e.printstacktrace ();
}
Client Client.java
Writer Writer = new OutputStreamWriter (Socket.getoutputstream ());
Writer.write ("okay");
Writer.flush ();
This is the problem of the code, the server has no output, at that time I mistakenly thought that the data was not received, then look at the information to know the problem in the Read method, this method if no data will be blocked (and call the Write.close () method, Read returns 1 out of the while loop, so if you want to get the data outside of the while loop, there are two methods
1 The client invokes the Write.close () method
2 The service end sets the jump condition in the while loop body, or the contract data length, or sends the string to have the end sign.
Modify the code as follows:
Client:
Writer Writer = new OutputStreamWriter (Socket.getoutputstream ());
Writer.write ("okay");
Writer.write ("EOF");//eof to end tag
Writer.flush ();
The server adds the following code in the while loop body:
while ((Len=reader.read (chars))!=-1) {
sb.append (new String (chars, 0, Len));
if (sb.tostring (). IndexOf ("EOF")!=-1) {
//judgment end tag break
;
}
}
Results the server successfully received the message, encountered the same troubled students, see if I made the same mistake.