[英]Sending and receiving files on socket
我正在從Java服務器向遠程Android客戶端發送文件。 我使用outputstream寫入字節。 在讀取這些字節時,read()方法將繼續嘗試在流結束之后讀取字節。 如果我在服務器端關閉outputstream
流,則讀取操作正常。 但是我必須再次在同一套接字上寫入文件,因此無法關閉輸出流嗎?
注意:我的代碼可以很好地共享單個文件
寫入文件的代碼
public static void writefile(String IP, String filepath, int port, OutputStream out) throws IOException {
ByteFileConversion bfc = new ByteFileConversion();
byte[] file = bfc.FileToByteConversion(filepath);
out.write(file, 0, file.length);
out.close(); // i donot want to close this and how can I tell reading side that stream is ended.
System.out.println("WRITTEN");
}
我在這里在Android上閱讀文件:
public Bitmap fileReceived(InputStream is) {
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
// System.out.println(imageInSD);
if (is != null) {
FileOutputStream fos = null;
OutputStream bos = null;
try {
bos = new FileOutputStream(imageInSD);
byte[] aByte = new byte[1024];
int bytesRead;
int index = 0;
DataInputStream dis = new DataInputStream(is);
while ((bytesRead = is.read(aByte)) > 0) {
index = bytesRead + index;
bos.write(aByte, 0, bytesRead);
// index = index+ bytesRead;
System.out.println("Loop" + aByte + " byte read are " + bytesRead + "whree index =" + index);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "out of loop");
java.io.FileInputStream in = new FileInputStream(imageInSD);
bitmap = BitmapFactory.decodeStream(in);
bitmap = BitmapFactory.decodeFile(imageInSD);
Log.i("IMSERVICE", "saved");
// if (bitmap != null)
// System.out.println("bitmap is "+ bitmap.toString());
} catch (IOException ex) {
// Do exception handling
// Log.i("IMSERVICE", "exception ");
System.out.println("ex");
}
}
return bitmap;
}
實際上,我想重置socket
連接
提前致謝
你需要:
DataOutputStream.writeLong()
,並在接收方使用DataInputStream.readLong()
。 從接收器的流中准確讀取那么多字節:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0) { out.write(buffer, 0, count); total += count; }
E&OE
其實我想重置套接字連接
實際上,您不想執行任何此類操作。
如果我不關閉輸出流,則另一側的讀取操作會停留在繼續讀取狀態
那是因為客戶端套接字的InputStream
仍在等待服務器發送一些數據包,從而阻塞了您的主線程。
解:
您可以將每個發送( OutputStream
)和讀取( InputStream
)數據包從套接字放入線程中,以防止在讀取和發送時阻塞主線程。
創建一個讀取InputStream
的線程,並讀取另一個OutputStream
的線程
邊注:
不要試圖關閉您的outputStream,因為文檔說它不能再次打開:
關閉返回的OutputStream將關閉關聯的套接字。
關閉的總協定是關閉輸出流。 關閉的流無法執行輸出操作,因此無法重新打開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.