You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Android平台Kotlin语言WebTransport双向通信实现示例

Android 上 Kotlin/Java 实现 WebTransport 双向通信方案

前置要求

  • Android 14(API Level 34)及以上系统版本,原生WebTransport API已纳入Android框架
  • 目标服务器需支持WebTransport协议(基于HTTP/3),并配置合法TLS证书

Datagram 模式实现(低延迟双向通信)

Datagram适用于无需可靠传输的低延迟场景,以下是Kotlin实现示例:

连接建立与双向通信

import android.net.http.WebTransport
import android.net.http.WebTransportClient
import android.net.http.WebTransportDatagramSession
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.URI

class WebTransportDatagramClient {
    private var datagramSession: WebTransportDatagramSession? = null

    fun connect(serverUri: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val client = WebTransportClient.Builder().build()
            val webTransport = client.connect(URI.create(serverUri), null).get()
            
            // 打开Datagram会话
            datagramSession = webTransport.openDatagramSession().get()
            
            // 启动数据监听
            listenForIncomingDatagrams()
            
            // 发送测试数据
            sendDatagram("Hello WebTransport Datagram!".toByteArray())
        }
    }

    private fun listenForIncomingDatagrams() {
        CoroutineScope(Dispatchers.IO).launch {
            val inputStream = datagramSession?.inputStream ?: return@launch
            val buffer = ByteArray(1024)
            while (true) {
                val bytesRead = inputStream.read(buffer)
                if (bytesRead == -1) break
                val receivedContent = String(buffer, 0, bytesRead)
                // 切换至主线程处理UI更新(如需要)
                CoroutineScope(Dispatchers.Main).launch {
                    // 处理接收的数据,例如更新UI组件
                }
            }
        }
    }

    fun sendDatagram(data: ByteArray) {
        CoroutineScope(Dispatchers.IO).launch {
            datagramSession?.outputStream?.apply {
                write(data)
                flush()
            }
        }
    }

    fun disconnect() {
        datagramSession?.close()
    }
}

Streams 模式实现(可靠双向通信)

Streams提供有序、可靠的数据传输,适合需确保数据完整性的场景,以下是双向流的Kotlin实现:

双向流建立与通信

import android.net.http.WebTransport
import android.net.http.WebTransportClient
import android.net.http.WebTransportBidirectionalStream
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import java.net.URI
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter

class WebTransportStreamClient {
    private var bidirectionalStream: WebTransportBidirectionalStream? = null

    fun connectAndOpenStream(serverUri: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val client = WebTransportClient.Builder().build()
            val webTransport = client.connect(URI.create(serverUri), null).get()
            
            // 打开双向流
            bidirectionalStream = webTransport.createBidirectionalStream().get()
            
            // 启动接收、发送协程
            launchReceiveLoop()
            launchSendLoop()
        }
    }

    private fun launchReceiveLoop() {
        CoroutineScope(Dispatchers.IO).launch {
            val reader = BufferedReader(InputStreamReader(bidirectionalStream?.inputStream))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                val receivedContent = line ?: return@launch
                // 切换至主线程处理UI更新(如需要)
                CoroutineScope(Dispatchers.Main).launch {
                    // 处理接收的数据,例如更新UI组件
                }
            }
        }
    }

    private fun launchSendLoop() {
        CoroutineScope(Dispatchers.IO).launch {
            val writer = OutputStreamWriter(bidirectionalStream?.outputStream)
            // 示例:循环发送数据,实际可根据业务逻辑触发
            repeat(5) {
                val message = "Client message ${it + 1}"
                writer.write(message)
                writer.flush()
                delay(1000)
            }
            writer.close()
        }
    }

    fun disconnect() {
        bidirectionalStream?.close()
    }
}

关键注意事项

  • 所有WebTransport操作必须在后台线程执行,避免阻塞主线程,示例中通过CoroutineScope(Dispatchers.IO)处理
  • 服务器需配置HTTP/3和WebTransport支持,连接URI必须使用https或wss协议(WebTransport仅支持加密连接)
  • 实际开发中需补充异常处理:示例省略了IOException、ExecutionException等异常捕获逻辑
  • 无需额外权限,但需确保设备网络正常且服务器可访问

内容的提问来源于stack exchange,提问作者Alphapage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:00:11