从套接字读取时 Java BufferedReader 转换循环挂起
我正在编写一个软件,它通过 HTTP 1.0 将外部源(我几乎无法控制)连接到 Java 中的本地数据库。我试图在连接关闭之前从响应正文中的数据库返回信息(外部源具有非常宽松的超时时间表)。我正在使用 BufferedReader 来从套接字读取流,但大部分主体(我们可以控制的唯一部分)在读取之前就被切断了。找到的解决方法是在正文中添加两行新行 (\n
) 以强制数据通过,但我觉得这可能会解决一个更大的问题。
是否有 BufferedReader
的替代方案,当套接字停止写入其缓冲区时发出信号,或者我是否滥用了 BufferedReader
?一些代码:
接受来自服务器的连接:
HttpHandler(ServerSocket serverSocket, Executor service) throws UnsupportedEncodingException, IOException
{
this.service = service;
Socket connectionSocket = serverSocket.accept();
InetAddress client = connectionSocket.getInetAddress();
input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), "UTF-8"));
output = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream(), "UTF-8"));
}
并将缓冲区处理成字符串:
@Override
public String[] call() throws Exception
{
String output[] = new String[2];
String line = new String();
StringBuilder builder = new StringBuilder();
while((line = input.readLine()) != null) //hangs here
{
if(line.startsWith("external-"))
{
builder.append(line + "\n");
}
}
buffer = builder.toString();
output = split(buffer);
System.out.println("Process Request Complete");
return output;
}
I'm writing a piece of software which connects an outside source (which I have near no control over) to a local database in Java via HTTP 1.0. I'm trying to return information from the database in the body of the response before the connection closes (the external source has a very lenient timeout schedule). I'm using a BufferedReader
to read the stream from the socket, but most of the body (the only part we have control over) is being cut off before it can be read. A workaround that was figured out was adding two new lines (\n
) to the body to force the data through, but I feel this may be working around a larger issue.
Is there an alternative to BufferedReader
that signals when a socket has stopped writing to its buffer, or am I misusing BufferedReader
? Some code:
Accepting the connection from the server:
HttpHandler(ServerSocket serverSocket, Executor service) throws UnsupportedEncodingException, IOException
{
this.service = service;
Socket connectionSocket = serverSocket.accept();
InetAddress client = connectionSocket.getInetAddress();
input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), "UTF-8"));
output = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream(), "UTF-8"));
}
And processing the buffer into a string:
@Override
public String[] call() throws Exception
{
String output[] = new String[2];
String line = new String();
StringBuilder builder = new StringBuilder();
while((line = input.readLine()) != null) //hangs here
{
if(line.startsWith("external-"))
{
builder.append(line + "\n");
}
}
buffer = builder.toString();
output = split(buffer);
System.out.println("Process Request Complete");
return output;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论