A Client Connection server applet, the server side can read the data sent by the client normally
However, when the client shuts down, the server also shuts down and throws the following exception:
Java.io.EOFExceptionat java.io.DataInputStream.readUnsignedShort (Datainputstream.java:323) at Java.io.DataInputStream.readUTF (Datainputstream.java:572) at Java.io.DataInputStream.readUTF ( Datainputstream.java:547) at Chatserver.main (Chatserver.java:
The server-side code is as follows:
ImportJava.io.*;Importjava.net.*;
Public classChatserver {
Public Static voidMain (string[] args) {Try{ServerSocket ss=NewServerSocket (7889); while(true) {Socket s=ss.accept ();D atainputstream dis=NewDataInputStream (S.getinputstream ()); while(true) {String str=Dis.readutf (); System.out.println (str); }}}Catch(IOException e) {e.printstacktrace ();}}}
The resulting exception is located in: String Str=dis.readutf ();
Have encountered this problem before, in the transmission process is not allowed to be concurrent access. So the data can be transmitted over and over, in fact, there are a lot of people in the running time will encounter eofexception, and then baffled, to various forums to ask the solution. In fact, I would like to say that this exception is not required to declare, that is, although it is an exception, but in fact, the end of the normal operation of the flag. EOF indicates that the end of the file has been read (String str = DIS.READUTF (); , the client has been disconnected, there is no content to read, and the send ends the natural connection is disconnected.
If this affects the correctness of your socket program, please take a quiet look at your program's business logic, instead of concentrating on sending and receiving methods. Because I was also plagued by such bugs for 1 of the day, many forum posts misunderstood a lot of the last lesson. If you go to readUTF () in the while loop, there is no problem at all, there is data to read, no automatic blocking. Then throw eofexception must be because the connection is broken still continue to read, what causes the connection broken? Must be the business logic where there are errors, such as Nullpoint, Classcaseexception, Arrayoutofbound, even if the program is large, it does not matter, at most as long as a single pace to find a bug and solve it quickly.
So which one is it? Of course the first one, because your client has been disconnected by you, so what should you do?
You can catch this client disconnects the exception eofexcption and then do the processing you need, try ... catch (eofexception) {System.out.println ("This is legal, the client is closed");}
Each time the client transmits the data, it transmits a null past, which is OK. Otherwise, the EOF is abnormal.
Source text: http://anwj336.blog.163.com/blog/static/8941520920087732313926/
Socket Programming Report Exception Java.io.EOFException