繁体   English   中英

检测服务器套接字关闭

[英]Detecting Server Socket Closing

我正在尝试在客户端和服务器之间发送一些号码。 关闭服务器之前,我要发送字符串“ 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);
}

}

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

另外,请勿将字符串与==进行比较,而应使用equals代替,因为结果返回false,您的while循环将在EOFException的闭合结果后尝试读取更多内容。

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

while(!(test = (String) ois.readObject()).equals("End")) {
    System.out.println(test);
    Object n1 = test;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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