หลังจากพบอุปกรณ์ระยะไกล จะมีการเรียกฟังก์ชัน handleIntent
และ
ได้เวลาเริ่มส่งข้อมูลระหว่างไคลเอ็นต์แล้ว ส่วนนี้ครอบคลุม
ขั้นตอนสำคัญ 4 ขั้นตอนในการรักษาการเชื่อมต่อให้ปลอดภัย
- เปิดการเชื่อมต่อ
- กำลังยอมรับการเชื่อมต่อ
- การส่งและรับข้อมูล
- ปิดการเชื่อมต่อ
เปิดการเชื่อมต่อ
หากต้องการเปิดการเชื่อมต่อเพื่อรับข้อมูลจากอุปกรณ์ระยะไกล ให้ใช้
ออบเจ็กต์ผู้เข้าร่วมที่ได้รับก่อนหน้านี้และระบุ CHANNEL_NAME
:
participant
.openConnection(CHANNEL_HELLO)
.onFailure { /* handle failure */}
.getOrNull()
?.let { connection ->
connection.send("Hello, world".toByteArray(UTF_8)).onFailure { /* handle failure */}
}
public void openConnection(Participant participant) {
Futures.addCallback(
participant.openConnectionFuture(CHANNEL_HELLO),
new FutureCallback<RemoteConnection>() {
@Override
public void onSuccess(RemoteConnection remoteConnection) {
// use remoteConnection object to pass data, e.g.:
sendDataToRemoteConnection(remoteConnection);
}
@Override
public void onFailure(Throwable t) {
// handle error opening a remote connection
}
},
mainExecutor);
}
private void sendDataToRemoteConnection(RemoteConnection remoteConnection) {
Futures.addCallback(
remoteConnection.sendFuture("Hello, world".getBytes()),
new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
// data sent successfully
}
@Override
public void onFailure(Throwable t) {
// handle error
}
},
mainExecutor);
}
ยอมรับ ส่ง/รับ และปิดการเชื่อมต่อ
การเชื่อมต่อที่ปลอดภัยต้องใช้อุปกรณ์ที่เป็นผู้รับยอมรับการเชื่อมต่อขาเข้า ก่อนที่จะรับข้อมูล หากต้องการยอมรับการเชื่อมต่อระยะไกล ให้ใช้รายการต่อไปนี้ ตัวอย่าง:
suspend fun acceptIncomingConnection(participant: Participant) {
val connection = participant.acceptConnection(CHANNEL_HELLO).getOrThrow()
connection.registerReceiver(
object : ConnectionReceiver {
override fun onMessageReceived(remoteConnection: RemoteConnection, payload: ByteArray) {
displayMessage(payload.toString(UTF_8))
}
override fun onConnectionClosed(
remoteConnection: RemoteConnection,
error: Throwable?,
reason: String?
) {
// handle connection closure
}
}
)
}
public void acceptIncomingConnection(Participant participant) {
// Registers call back to accept incoming remote connection
Futures.addCallback(
participant.acceptConnectionFuture(CHANNEL_HELLO),
new FutureCallback<>() {
@Override
public void onSuccess(RemoteConnection result) {
receiveData(result);
}
@Override
public void onFailure(Throwable t) {
// handle connection error
}
},
mainExecutor);
}
private void receiveData(RemoteConnection remoteConnection) {
remoteConnection.registerReceiver(
new ConnectionReceiver() {
@Override
public void onMessageReceived(RemoteConnection remoteConnection, byte[] payload) {
displayMessage(new String(payload, UTF_8));
}
@Override
public void onConnectionClosed(
RemoteConnection remoteConnection,
@Nullable Throwable error,
@Nullable String reason) {
// handle connection closure
}
});
}