更新记录
1.0.0(2026-09-13) 下载此版本
初版
平台兼容性
uni-app(3.8.3)
| Vue2 | Vue3 | Chrome | Safari | app-vue | app-nvue | Android | iOS | 鸿蒙 |
|---|---|---|---|---|---|---|---|---|
| - | - | - | - | - | - | 4.4 | - | - |
| 微信小程序 | 支付宝小程序 | 抖音小程序 | 百度小程序 | 快手小程序 | 京东小程序 | 鸿蒙元服务 | QQ小程序 | 飞书小程序 | 小红书小程序 | 快应用-华为 | 快应用-联盟 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| - | - | - | - | - | - | - | - | - | - | - | - |
其他
| 多语言 | 暗黑模式 | 宽屏模式 |
|---|---|---|
| √ | √ | √ |
sl-uniplugin-tcp-udp TCP/UDP 网络通信插件
简介
基于 Java Socket / DatagramSocket 的 TCP/UDP 网络通信 UTS 插件,支持:
- TCP 客户端(连接、发送、接收、关闭)
- TCP 服务端(监听端口、接收客户端数据、向客户端发送数据)
- UDP 发送与接收
所有收发数据均使用 UTF-8 编解码,支持中文传输。
目录结构
sl-uniplugin-tcp-udp/
├── package.json
├── README.md
└── utssdk/app-android/
├── index.uts # TCP/UDP 实现
├── config.json # 依赖与构建配置
└── AndroidManifest.xml # 权限声明 (INTERNET, ACCESS_NETWORK_STATE)
权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
依赖配置
config.json
{
"minSdkVersion": 21,
"dependencies": [
{ "id": "org.jetbrains.kotlin:kotlin-stdlib", "version": "1.8.22" }
],
"abiFilters": ["arm64-v8a", "armeabi-v7a"]
}
build.gradle(Android 工程侧)
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.sl.sl_uniplugin_tcp_udp'
compileSdk 35
defaultConfig {
minSdk 21
consumerProguardFiles "consumer-rules.pro"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = '11'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.10.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
// uts 插件运行时依赖(io.dcloud.uts.* / io.dcloud.uniapp.*)
compileOnly fileTree(dir: "${rootProject.projectDir}/simpleDemo/libs", include: ['*.aar', '*.jar'])
}
proguard-rules.pro / consumer-rules.pro
# 保留 UTSJSONObject 序列化
-keep class io.dcloud.uts.UTSJSONObject { *; }
API
TCP 客户端
tcpConnect(options, callback)
连接 TCP 服务端。在子线程执行,不阻塞 UI。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.host | String | 是 | 服务端 IP 地址 |
| options.port | Number | 是 | 服务端端口 |
| options.timeout | Number | 否 | 连接超时(毫秒),默认 5000 |
回调返回值:
// 成功
{ "code": 0, "success": true, "msg": "Connected" }
// 失败
{ "code": 1, "success": false, "msg": "Connect failed: ..." }
示例:
import { tcpConnect } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpConnect({ host: '192.168.1.100', port: 8080, timeout: 5000 }, (res) => {
if (res.code === 0) {
console.log('TCP 已连接')
} else {
console.error('连接失败:', res.msg)
}
})
tcpSend(options, callback)
通过已建立的 TCP 连接发送数据(UTF-8 编码,支持中文)。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.data | String | 是 | 要发送的文本数据 |
示例:
import { tcpSend } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpSend({ data: '你好 TCP' }, (res) => {
if (res.code === 0) {
console.log('发送成功')
} else {
console.error('发送失败:', res.msg)
}
})
tcpClose(options, callback)
关闭 TCP 连接,释放 Socket 和流资源。
示例:
import { tcpClose } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpClose({}, (res) => {
console.log('TCP 已关闭')
})
tcpIsConnected()
返回 TCP 是否处于已连接状态(同步)。
import { tcpIsConnected } from '@/uni_modules/sl-uniplugin-tcp-udp'
const connected = tcpIsConnected()
tcpGetReceivedData()
获取 TCP 最新接收数据(前端轮询)。由于 UTS callback 一次性限制,接收数据通过此方法轮询获取。
返回值:
{
"code": 0,
"success": true,
"type": "tcp",
"data": "收到的文本",
"from": "server",
"timestamp": 1234567890123
}
轮询示例:
import { tcpGetReceivedData } from '@/uni_modules/sl-uniplugin-tcp-udp'
let lastTs = 0
setInterval(() => {
const res = tcpGetReceivedData()
if (res && res.timestamp > lastTs) {
lastTs = res.timestamp
console.log('TCP 收到:', res.data)
}
}, 200)
TCP 服务端
tcpStartServer(options, callback)
启动 TCP 服务端,监听指定端口。在子线程执行,不阻塞 UI。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.port | Number | 是 | 监听端口 |
示例:
import { tcpStartServer } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpStartServer({ port: 9090 }, (res) => {
if (res.code === 0) {
console.log('服务端已启动')
}
})
tcpServerSend(options, callback)
TCP 服务端向已连接的客户端发送数据(UTF-8 编码,支持中文)。需要有客户端已连接才能发送。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.data | String | 是 | 要发送的文本数据 |
示例:
import { tcpServerSend } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpServerSend({ data: '你好,来自服务端' }, (res) => {
if (res.code === 0) {
console.log('服务端发送成功')
} else {
console.error('发送失败:', res.msg)
}
})
tcpStopServer(options, callback)
停止 TCP 服务端,关闭 ServerSocket 和所有客户端连接。
示例:
import { tcpStopServer } from '@/uni_modules/sl-uniplugin-tcp-udp'
tcpStopServer({}, (res) => {
console.log('服务端已停止')
})
tcpServerIsRunning()
TCP 服务端是否运行中(同步)。
import { tcpServerIsRunning } from '@/uni_modules/sl-uniplugin-tcp-udp'
const running = tcpServerIsRunning()
tcpServerGetReceivedData()
获取 TCP 服务端最新接收数据(前端轮询)。
返回值:
{
"code": 0,
"success": true,
"type": "tcp-server",
"data": "客户端发来的文本",
"from": "192.168.1.50:12345",
"timestamp": 1234567890123
}
UDP
udpSend(options, callback)
发送 UDP 数据包(UTF-8 编码,支持中文)。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.host | String | 是 | 目标 IP 地址 |
| options.port | Number | 是 | 目标端口 |
| options.data | String | 是 | 要发送的文本数据 |
示例:
import { udpSend } from '@/uni_modules/sl-uniplugin-tcp-udp'
udpSend({ host: '192.168.1.100', port: 8080, data: '你好 UDP' }, (res) => {
if (res.code === 0) {
console.log('UDP 发送成功')
}
})
udpStartReceive(options, callback)
启动 UDP 接收,监听指定端口。在子线程执行,不阻塞 UI。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| options.port | Number | 是 | 监听端口 |
示例:
import { udpStartReceive } from '@/uni_modules/sl-uniplugin-tcp-udp'
udpStartReceive({ port: 9090 }, (res) => {
if (res.code === 0) {
console.log('UDP 接收已启动')
}
})
udpStopReceive(options, callback)
停止 UDP 接收,关闭 DatagramSocket。
示例:
import { udpStopReceive } from '@/uni_modules/sl-uniplugin-tcp-udp'
udpStopReceive({}, (res) => {
console.log('UDP 接收已停止')
})
udpIsReceiving()
UDP 是否接收中(同步)。
import { udpIsReceiving } from '@/uni_modules/sl-uniplugin-tcp-udp'
const receiving = udpIsReceiving()
udpGetReceivedData()
获取 UDP 最新接收数据(前端轮询)。
返回值:
{
"code": 0,
"success": true,
"type": "udp",
"data": "收到的文本",
"from": "192.168.1.50:12345",
"timestamp": 1234567890123
}
技术细节
- 子线程执行:连接、发送、接收均在子线程执行,不阻塞 UI
- UTF-8 编解码:所有文本数据使用 UTF-8 编解码,支持中文等多字节字符
- 编码:
str.toByteArray(Charset.UTF_8)(Kotlin 扩展方法,非 JavagetBytes()) - 解码:
bytes.toString(Charset.UTF_8)(Kotlin 扩展方法,非new String(bytes, charset))
- 编码:
- 轮询接收:由于 UTS callback 在 Weex 引擎下只能被 JS 端接收一次,接收数据通过
getReceivedData()方法轮询获取,用timestamp字段判断新数据 - Runnable 语法:UTS 中用
new class implements Runnable { override run(): void {} },不支持new Runnable({ run: () => {} })和 Kotlin 的object : Runnable {}语法 - ByteArray:UTS 中用 Kotlin 原生
ByteArray类型,数组大小用.size属性,子数组用.copyOfRange(from, to) - TCP 服务端客户端管理:当前实现保存最后连接的客户端输出流,
tcpServerSend向该客户端发送数据;客户端断开时自动清理引用
UTS 开发注意事项
- minSdkVersion 21(Android 5.0+)
- 网络权限:需要在
AndroidManifest.xml中声明INTERNET和ACCESS_NETWORK_STATE权限 - 不要在主线程做网络操作:Android 禁止在主线程进行网络请求,本插件已自动在子线程执行
- 轮询间隔:建议轮询间隔 200-300ms,页面卸载时需清除定时器
- 端口占用:UDP 接收端口和 TCP 服务端端口不能被其他应用占用
- 数据格式:当前仅支持 UTF-8 文本数据,二进制数据需自行处理 Base64 编解码
- 不支持
import ... as:UTS 不支持import String as JString from 'java.lang.String'语法,java.lang.String在 Kotlin 环境中默认可用 - 不支持
getBytes():UTS 的string映射到 KotlinString,需用toByteArray()扩展方法 - UTS callback 一次性限制:在 uni-app Vue3(非 uni-app x)项目 + App-Android 真机环境下,UTS callback 只能被 JS 端接收一次。本插件的接收数据通过轮询
getReceivedData()获取,不依赖多次 callback

收藏人数:
下载插件并导入HBuilderX
赞赏(0)
下载 108
赞赏 1
下载 12592869
赞赏 1949
赞赏
京公网安备:11010802035340号