C#HttpListener重置连接

时间:2015-07-15 13:16:34

标签: c# android

我正在构建一个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();

1 个答案:

答案 0 :(得分:1)

事实证明,connection.getContentLength()并不总是与input.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的大小过大会导致它再次失败(例如,使用1024,会出现同样的问题)。

相关问题