據我瞭解,你問了三個問題。
如何發送每當服務器返回數據文件:你基本上打開到服務器的連接(例如http
,但也可能是任何其他TCP或基於UDP的協議)。然後你聽取傳入的數據;一旦你收到數據,你就會觸發你想要的任何動作。這是一個起點,一些相關的呼叫時您的服務器不使用http
(未經測試,請查閱詳細信息和替代的文檔):
Socket s = new Socket('your.server.com', 47000);
s.connect();
SocketChannel c = s.getChannel();
ByteBuffer buffer = new ByteBuffer(1);
c.read(buffer); // blocks until bytes are available
如何自動啓動藍牙連接,獲取目標設備的BluetoothDevice
對象,然後連接到它 - 如在BluetoothChat演示中。
如何通過藍牙發送文件/超過1024個字節:是的,你有你的數據分割成塊的發送方和重組它們在接收端(記的實際數據之前發送的文件大小,因此接收者知道文件何時完成)。你也可以使用合理的較大的字節緩衝區。我建議使用64 Kb的最大塊大小:這允許您重新發送塊而沒有太多(時間)成本,並且不會消耗太多內存。
作爲首發關於3,這樣的事情可以在發送端的核心(未經測試並沒有錯誤處理,只是爲了讓這個想法):
// Send the file size
OutputStream out = socket.getOutputStream();
ByteBuffer header = ByteBuffer.allocate(8);
header.putLong(file.length();
out.write(header.array());
// Send the file in chunks
byte buffer[1024];
InputStream in = new BufferedInputStream(new FileInputStream(file));
int length = in.read(buffer);
while (length > 0) {
out.write(buffer, 0, length);
if (length < 1024) break;
length = in.read(buffer, 0, sizeof(buffer));
};
...和接收方:
// Receive and unmarshal the file size
InputStream in = socket.getInputStream();
ByteBuffer header = ByteBuffer.allocate(8);
byte buffer[1024];
in.read(buffer, 0, 8);
header.put(buffer);
long filesize = header.getLong();
long receivedBytes = 0;
// Receive the file
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
int length = in.read(buffer);
while ((receivedBytes < filesize) && (length > 0)){
out.write(buffer, 0, length);
receivedBytes += length;
length = in.read(buffer);
}
if (receivedBytes != filesize) ... // Assure the transfer was successful
嗨domsom:感謝您的寶貴答覆。我在使用藍牙聊天示例通過藍牙發送簡單圖像文件時遇到問題。其實,我的要求是通過藍牙發送任何文件。現在我正在嘗試發送一個圖像文件,爲此我該如何設置緩衝區大小,如何接收小塊數據並在接收端進行組合。可以請你分享我的代碼。 –
我沒有代碼,但我只是添加了一些示例行來給出這個想法...... – domsom
你是在說兩個不同的項目。一個是客戶端,另一個是服務器。現在我正在修改藍牙聊天示例。在那個示例中,他們已將聊天消息轉換爲字節數組。這裏我必須將文件轉換爲字節數組並且必須傳遞字節數組的參數。現在我懷疑我是否想要實現雙向溝通,如藍牙聊天。必須從藍牙聊天工作兩端傳輸文件。 –