When the socket receives data, it often throws Java. io. the eofexception is abnormal and there are no clear causes or prompts. Many people are asking this question on the Internet, but no practical solution is found. After research, the problem is solved. The exception stack information is as follows: Java. Io. eofexception
At java. Io. datainputstream. readfully (datainputstream. Java: 178)
At java. Io. datainputstream. readutf (datainputstream. Java: 565)
At java. io. datainputstream. readutf (datainputstream. java: 522) Java's explanation for this is also vague: public class eofexceptionextends ioexception throws this exception when the input process unexpectedly reaches the end of the file or stream.
This exception is mainly used by the data input stream to indicate that it reaches the end of the stream. Note that many other input operations return a special value to reach the end of the stream, rather than throwing an exception.
We can see from the above prompts that the exception is thrown when the end of the stream is reached because we do not know the end of the stream. Since you don't know the end, simply set a cache and read a batch of data and then output it. During the warranty period, you can set the cache value to a greater value, so that you can completely receive the desired content at a time, so that you can read the desired content at a time, avoiding loop acquisition. The following code is used :......
Private Static final int buffer_size = 1024*1024;
......
Socket socket = new socket (CFG. getip (), integer. parseint (sysparamstoolkit. getproperty ("socketport ")));
String charset = sysparamstoolkit. getproperty ("socke. rexml. charset"); // character set encoding sent by socket
Try {
Outputstream dos = socket. getoutputstream ();
Dos. Write (xmlcmd. getbytes (charset ));
Dos. Flush ();
Datainputstream Dis = new datainputstream (socket. getinputstream ());
Char [] DATA = new char [buffer_size];
Bufferedreader BR = new bufferedreader (New inputstreamreader (socket. getinputstream (), charset ));
Int Len = Br. Read (data );
String rexml = string. valueof (data, 0, Len); // receives a string
} Catch (exception e ){
Return false;
} Finally {
If (socket. isconnected ())
Socket. Close ();
}
After the above processing, there will be no problem. The cache size buffer_size is determined based on the size of the content you want to receive.