0

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)
4

1 回答 1

0

我认为答案是这就是发生的事情。这EOFException是告诉调用者它已达到 EOF的唯一方法。DataInputStream因此,如果您的服务器尝试在您的客户端关闭套接字时进行读取,则会发生这种情况。

有两种解决方案:

  • 捕获并处理 EOFException。

  • 修改您的“协议”,以便客户端(以某种方式)在发送最后一条消息时告诉服务器......并且将关闭套接字。


关闭DataOutputStream客户端是一个好主意,但它可能不会解决问题。ADataOutputStream没有缓冲,SocketOutputStream也没有,所以不应该有数据被刷新。(网络协议栈中的任何数据未完成数据都应该在SocketorOutputStream关闭时传输。)

于 2013-06-30T05:18:08.863 回答