我正在使用TCP套接字將文件從C#客戶端傳輸到Java服務器。在C#客戶端上,我將文件轉換爲字節數組進行傳輸並使用NetworkStream發送。讀取Java中的C#字節數組
在Java服務器上,我使用以下代碼將接收到的字節數組轉換回文件;
public void run() {
try {
byte[] byteArrayJAR = new byte[filesize];
InputStream input = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(
"Controller " + controllerNumber + ".jar");
BufferedOutputStream output = new BufferedOutputStream(fos);
int bytesRead = input.read(byteArrayJAR, 0, byteArrayJAR.length);
int currentByte = bytesRead;
System.out.println("BytesRead = " + bytesRead);
do {
bytesRead = input.read(
byteArrayJAR,
currentByte,
(byteArrayJAR.length - currentByte));
if (bytesRead >= 0) {
currentByte += bytesRead;
}
}
while (bytesRead > -1);
output.write(byteArrayJAR, 0, currentByte);
output.flush();
output.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
的代碼,如果接收到的字節數組來自與Java編程的客戶端,但對於C#客戶代碼在掛起上述工作do-while循環在bytesRead = input.read(...)方法。
有沒有人知道爲什麼代碼掛在C#客戶端而不是Java客戶端?根據println消息的輸出數據肯定是由InputStream接收的,並且在bytesRead變量初始化時讀取一次,但不在do-while循環中讀取。
任何解決方案或建議,以克服這個問題將受到歡迎。
Regards,
Midavi。基於
向我們展示您的C#代碼。你可能錯過了一個'Flush()'? – dtb 2012-01-18 16:53:20
如果文件大小不小於或等於有效發送的數據,則read()將被阻止。你不應該試圖猜測你要接收的數據的大小,你必須保持閱讀,直到流爲空。 – Viruzzo 2012-01-18 16:55:36