Socket编程:EOFException详解

411 阅读1分钟

EOFException

image-20230817100010306.png

  • IO异常的子类,End of File表示流的尾部。
  • 流已经到末尾了,而大部分做法是以特殊值的形式返回给我们,而不是抛异常。
  • 异常是被主动抛出来的,而不是底层或者编译器主动返回。

返回特殊值处理方式

InputStream.read()

Returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Throws:

IOException - If an I/O error occurs

BufferedReader.readLine()

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Throws:

IOException - If an I/O error occurs

EOFException Example

package com.cclu.socket;

import java.io.*;
import java.net.Socket;

public class GreetingClient {
    public static void main(String[] args) {
        String serverName = "127.0.0.1";
        int port = Integer.parseInt("1427");
        Socket client;
        try {
            System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
            // init the socket of the client
            client = new Socket(serverName, port);
            System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            out.writeUTF("Hello from " + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("服务器响应: " + in.readUTF());
            client.close();
        } catch (IOException e) {
            System.out.println();
        }
    }
}

image-20230817102142543.png

处理建议

对于这种异常的一般解决方法就是,捕获,可以记录日志,也可以不做处理,捕获异常以后,把之前读到的数据进行后续的处理就可以了,因为那就是所以的数据。还有就是如果打算记录日志,不要把它的堆栈信息打印出来,容易给人以错觉。毕竟EOFException实质上只是一个消息而已。

当然抛异常的做法还是有一些偏激,但是当ObjectInputStream在不知道读取对象数量的情况下,确实无法判断是否读完,除非你把之前写入对象流的数量记录下来。所以说出现这个异常时就认真分析一下,这个异常是不是代表一个信息。