簡體   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