发现远程设备后,系统会调用 handleIntent
函数,并且
是时候开始在客户端之间传递数据了。本部分介绍了
保持安全连接的四个必要步骤:
- 打开连接
- 正在接受连接
- 发送和接收数据
- 断开连接
打开连接
要打开连接以从远程设备接收数据,请使用
之前收到的参与者对象,并指定 CHANNEL_NAME
:
Kotlin
participant .openConnection(CHANNEL_HELLO) .onFailure { /* handle failure */} .getOrNull() ?.let { connection -> connection.send("Hello, world".toByteArray(UTF_8)).onFailure { /* handle failure */} }
Java
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); }
接受、发送/接收以及关闭连接
安全连接要求接收方设备接受传入连接 然后再接收数据如需接受远程连接,请使用以下 snippet:
Kotlin
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 } } ) }
Java
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 } }); }