检测服务器套接字关闭

时间:2018-07-27 18:11:14

标签: java sockets

我正在尝试在客户端和服务器之间发送一些号码。关闭服务器之前,我要发送字符串“ End”。客户端检查正在读取的字符串是否为“ End”。如果否,它将捕获字符串。但是,我面临着两个问题。 首先,我发送了7个号码,但由于某种原因,我得到了四个号码(每个其他号码)。例如,我从服务器[79、20、42、0、10、31、21]发送这些数字,并在客户端中获得这些数字:[79、42、10、21]。 第二,即使我正在检查对象,也遇到了EOFException。

服务器代码如下:

public class main {

public static void main(String[] args) throws IOException {

    // Create a Socket
    int port = 6000;
    @SuppressWarnings("resource")
    ServerSocket sersock = new ServerSocket(port);
    Socket sock = sersock.accept( );

    OutputStream ostream = sock.getOutputStream(); 
    ObjectOutputStream pwrite = new ObjectOutputStream(ostream);

    int q = 7;

    SecureRandom rand = new SecureRandom();
    int[] list = new int [q];

    for (int i = 0; i < q; i++)
    {
        int num = rand.nextInt(100);
        list[i] = num;
        String n1 =  Integer.toString(num);
        pwrite.writeObject(n1);
    }
    System.out.println(Arrays.toString(list));

    // Close the socket
    pwrite.writeObject("End");
    sock.close();
}

}

客户端代码如下:

public class main {

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
    // Create Socket
    int port = 6000;
    Socket sock = new Socket("localhost", port);
    ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
    String test = "";
    ArrayList<String> numlist = new ArrayList<String>();

    //while(! sock.isClosed())
    while((test = (String) ois.readObject()) != "End")
    {
        System.out.println(test);
        Object n1 = ois.readObject();
        if(n1 instanceof String)
        {
            String n2 = (String) n1;
            numlist.add(n2);
        }
    }

    System.out.println("The collected clues are: ");
    System.out.println(numlist);
}

}

1 个答案:

答案 0 :(得分:2)

您在while语句和while块内部调用readObject,使其读取两次。

此外,请勿将字符串与==进行比较,而是使用equals,因为结果返回false,您的while循环将在对EOFException进行封闭运算后尝试读取更多内容。

使用您已经阅读过一次的变量“ test”

[scrollbarH]="false"