简体   繁体   中英

Java TCP Socket programming throwing IO exceptions

I have written a client-server TCP Socket program such that the client will enter a string and that will be displayed by the server(echo program)... the condition is when I enter bye the program should exit... Well and good the client program is exiting ... but the server program is exiting with a java.io.DataInputStream.readUTF() and readFully exceptions.. plz help me.. whats wrong in the code...

/*Client*/

import java.net.*;
import java.io.*;
public class echoclient {

public static void main(String args[]) throws Exception
{
    Socket soc = new Socket("127.0.0.1",4000);
    OutputStream sout = soc.getOutputStream();
    DataOutputStream out = new DataOutputStream(sout);
    DataInputStream din = new DataInputStream(System.in);
    while(true)
    {
    String message = din.readLine();
    if(message.equals("bye"))
        break;
    out.writeUTF(message);
    }
    soc.close();
}

}

   /*Server*/
import java.io.*;
import java.net.*;
public class echoserver {

public static void main(String args[]) throws Exception
{
    ServerSocket server = new ServerSocket(4000);
    Socket soc = server.accept();
    System.out.println("Server Started....");

    InputStream sin = soc.getInputStream();
    DataInputStream in = new DataInputStream(sin);
    while(true)
    {
    String fromClient = in.readUTF();
    if(fromClient.equals("bye"))
        {break;}
    System.out.println("Client says : "+fromClient);
    }
    soc.close();server.close();
}
 }

Exception:

    Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.DataInputStream.readUTF(DataInputStream.java:589)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at echoserver.main(echoserver.java:15)

I think that the answer is that that's just what happens. The EOFException is the only way that the DataInputStream tell the caller that it has reached EOF. So if your server attempts to read when the socket has been closed by your client, that's what will happen.

There are two solutions:

  • Catch and handle the EOFException.

  • Modify your "protocol" so that the client (somehow) tells the server when it has sent the last message ... and is going to close the socket.


Closing the DataOutputStream on the client side is a good idea, but it probably won't solve the problem. A DataOutputStream is not buffered and neither is a Socket's OutputStream , so there should be no data to be flushed. (Any data outstanding data in the network protocol stack should be transmitted when the Socket or OutputStream is closed.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM