套接字输入流在最终读取时挂起。处理这个的最佳方法? [英] Socket input stream hangs on final read. Best way to handle this?

查看:115
本文介绍了套接字输入流在最终读取时挂起。处理这个的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点难过如何避免我的插座挂在阅读上。这是我的代码:

I'm a bit stumped on how to avoid my socket hanging on read. Here's my code:

    Socket socket = new Socket("someMachine", 16003);
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();
    try {
        outputStream.write(messageBuffer.toByteArray());
        outputStream.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer response = new StringBuffer();
        int result;
        while ((result = in.read()) != -1) {
            response.append(Character.toChars(result));
            System.out.println(result);
        }
        System.out.println("Done!");  //never gets printed
     } catch (...) {}

上面的代码成功读取流中的所有数据,但随后挂起。在网上阅读我期待从服务器(我无法控制)收到-1表示我已经到达流的末尾,但我得到了这个:

The above code successfully reads all the data from the stream but then hangs. Reading up on the net I was expecting to receive a -1 from the server (which I can't control) to indicate that I had reached the end of stream but instead I get this:

(Lots of data above this point)
57
10
37
37
69
79
70
10

然后挂起。所以,我的问题是:

It then hangs. So, my questions are:

1)我是否编码错误或服务器响应有问题?

1) Have I coded this wrong or is there an issue with the server's response?

2)如果服务器的响应存在问题(即没有返回-1),我该怎样解决这个问题(即挂起时停止读取)。

2) If there is an issue with the server's response (i.e. no -1 being returned), how can I work around this (i.e. to stop reading when it hangs).

任何帮助表示赞赏!

推荐答案

只停止读取会挂起的问题是2例会发生这种情况:

The problem with just stopping where read would hang is that this can happen in 2 cases:

1:服务器没有更多数据要发送

1: server doesn't have any more data to send

2:服务器发送了更多数据,但是由于网络过载,你的客户还没有收到它。

2: The server has sent more data, but your client has not received it yet due to network overload.

你只想在第一种情况下真正停止读取,但你想要读取阻止第二种情况。

And you only want to really stop reading in the first case, but you want read to block in the second case.

解决这个问题的方法是建立一个传输协议(标准),它允许服务器告诉客户端它希望发送多少数据。

The way to solve this is to make a transfer protocol(Standard) which allows the server to tell the client how much data it expects to send.

如果服务器事先知道总数据大小,只需先发送传输中的总字节数,然后再发送数据。这样客户端就知道它什么时候收到了所有数据。

If the server knows the total data size in advance, simply start by sending the total number of bytes in the transfer, and then send the data. That way the client knows when it have received all data.

(或者服务器完成后只需关闭连接。那样读取会失败,但这只能起作用如果您将来不需要连接)

(Or the server can simply close the connection when done. That way read should fail, but this only work if you don't need the connection in the future)

这篇关于套接字输入流在最终读取时挂起。处理这个的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆