繁体   English   中英

C#HttpListener重置连接

[英]C# HttpListener resets connection

我正在使用Android应用程序构建一个系统,该应用程序使用HTTPURLConnection与另一端进行通信,该应用程序是C# HttpListener 他们通过此通道与XML数据进行通信。

除一些较大的数据外,这非常有效。 当我尝试传达这些信息时,我看到来自Android的XML到达了C#应用程序,并且C#应用程序确实做出了响应。 但是,在数据到达Android之前,我得到了“对等连接重置”。 例外。

这是Android代码:

URL url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(tel.length());
connection.setReadTimeout(30000);

// write our telegram...
OutputStream output = new BufferedOutputStream(connection.getOutputStream());
output.write(tel.getBytes());
output.flush();

这是阅读的答复:

InputStream input = new BufferedInputStream(connection.getInputStream());
if (connection.getResponseCode() == HttpStatus.SC_OK) {
    String r = null;
    byte cbuf[] = new byte[connection.getContentLength()];
    if (input.read(cbuf, 0, connection.getContentLength()) != -1) {
        r = new String(cbuf);
    }
    reply = Telegram.fromString(r);
} else {
   throw new ProtocolException("HTTP Error code: "+connection.getResponseCode());
}

这是C#代码:

httpListener = new HttpListener();
httpListener.Prefixes.Add(String.Format("http://*:{0}/", port);
httpListener.Start();

事实证明, connection.getContentLength()并不总是与input.read()读取的字节数匹配,因此read调用会等待(最终,服务器会重置,因为我猜发送完成了)。

为了解决这个问题,我将接收方改写为:

int bufs = 256, read;
ByteArrayOutputStream cbuf = new ByteArrayOutputStream(bufs);
byte[] tempbuf = new byte[bufs];

while ((read = input.read(tempbuf, 0, bufs)) != -1) {
    Log.d(PocketApplication.TAG, "Read "+read+" bytes.");
    cbuf.write(tempbuf);
}

现在可以正常工作了。 使bufs的大小太bufs导致它再次失败(例如,对于1024,会发生相同的问题)。

暂无
暂无

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

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