更新记录

1.0.2(2025-08-28) 下载此版本

删除多余代码,修改可能存在的类型问题

1.0.1(2025-08-27) 下载此版本

让ai优化isConnected处理,实测比原来好

1.0.0(2025-08-27) 下载此版本

根据https://ext.dcloud.net.cn/plugin?name=moe-tcp-client源码,修改为uts插件,解决app杀后台没有断开连接的问题,未作其他测试,uni-app支持版本不清楚直接在最新上测试的4.76

查看更多

平台兼容性

云端兼容性

阿里云 腾讯云 支付宝云

uni-app(4.76)

Vue2 Vue3 Chrome Safari app-vue app-nvue Android Android插件版本 iOS 鸿蒙
- - × × - - 5.0 1.0.0 × ×
微信小程序 支付宝小程序 抖音小程序 百度小程序 快手小程序 京东小程序 鸿蒙元服务 QQ小程序 飞书小程序 快应用-华为 快应用-联盟
× × × × × × × × × × ×

uni-app x(4.76)

Chrome Safari Android iOS 鸿蒙 微信小程序
- - - - - -

zsl-tcp

引入方式

import zslTcp from '@/uni_modules/zsl-tcp'
const client = new zslTcp();

方法

建立连接

client.connect({
  ip: 'xxx.xxx.xxx.xxx',
  port: 6900
}, result => {
  // 连接结果
})

断开连接

client.disconnect();

判断是否处于连接

client.isConnected(res => {

});

发送字符串消息

client.sendStr({
  message: '发送的内容'
});

发送Hex字符串消息

client.sendHexStr({
  message: '发送的内容'
});

注册消息监听

监听服务端消息

client.onReceive(res => {

});

监听通讯断连

client.onDisconnect(res => {

});

服务端消息res返回值示例说明

{
    "code": 1,
    "data": "内容",
    "dataBinary": [-12,0,12],// 随便写的,带符号字节流
    "msg": "收到消息"
}
字段 字段类型 解析备注
code int 错误码:1正常、0失败
msg String 消息反馈
data String 消息数据(字节流UTF8编码后的字符串)
dataBinary String 消息数据原始字节流

如果服务端消息是文本消息,使用data即可 如果服务端消息是十六进制数据,为防止编码问题,可直接使用 dataBinary 转换

下面给出一个字节流转Hex字符串方法

/**
 * 字节流转Hex字符串
 * @params base64Str
 */
// -127到127
byteArrayToHex2(byteArray, length=byteArray.length) {
    let hex = '';
    for (let i = 0; i < length; i++) {
        // 将字节值转换为无符号并格式化为十六进制
        const hexByteValue = (byteArray[i] & 0xFF).toString(16).padStart(2, '0');
        hex += hexByteValue;
    }
    return hex;
}

额外修改

以下是多连接修改方法来自ai提供参考,不包含在插件内,可自行修改测试

import SocketTransceiver from 'uts.sdk.modules.zslTcp.utils.SocketTransceiver';
import TcpClient from 'uts.sdk.modules.zslTcp.utils.TcpClient';

type OutJSON = {
    code: number,
    msg: string,
    data?: string,
    dataBinary?: ByteArray
}

// 连接配置类型
type ConnectionConfig = {
    id: string,
    ip: string,
    port: number,
    onReceiveCallback?: ((id: string, res: OutJSON) => void) | null,
    onConnectCallback?: ((id: string, res: OutJSON) => void) | null,
    onDisconnectCallback?: ((id: string, res: OutJSON) => void) | null
}

// 创建一个具体的 TcpClient 实现类
class ConcreteTcpClient extends TcpClient {
    private id: string;
    private config: ConnectionConfig;

    constructor(id: string, config: ConnectionConfig) {
        super();
        this.id = id;
        this.config = config;
    }

    override onConnect(transceiver: SocketTransceiver): void {
        console.log("zslTcp", `Client ${this.id} Connected`);
        if (this.config.onConnectCallback != null) {
            const outJson: OutJSON = {
                code: 1,
                msg: "Connected",
                data: ""
            };
            this.config.onConnectCallback(this.id, outJson);
        }
    }

    override onConnectFailed(): void {
        if (this.config.onConnectCallback != null) {
            const outJson: OutJSON = {
                code: 0,
                msg: "Connect failed",
                data: ""
            }
            this.config.onConnectCallback(this.id, outJson);
        }
    }

    override onReceive(transceiver: SocketTransceiver, s: string, b: ByteArray): void {
        if (this.config.onReceiveCallback != null) {
            const outJson: OutJSON = {
                code: 1,
                msg: "Received",
                data: s,
                dataBinary: b
            }
            this.config.onReceiveCallback(this.id, outJson);
        }
    }

    override onDisconnect(transceiver: SocketTransceiver): void {
        if (this.config.onDisconnectCallback != null) {
            const outJson: OutJSON = {
                code: 0,
                msg: "Disconnected",
                data: ""
            }
            this.config.onDisconnectCallback(this.id, outJson);
        }
    }

    // 正确重写父类方法
    override connect(hostIP: string | null, port: number): void {
        super.connect(hostIP, port);
    }

    override disconnect(): void {
        super.disconnect();
    }

    override isConnected(): boolean {
        return super.isConnected();
    }

    override getTransceiver(): SocketTransceiver | null {
        return super.getTransceiver();
    }
}

// TCP连接管理器
class TcpConnectionManager {
    private connections: Map<string, ConcreteTcpClient> = new Map();
    private globalReceiveCallback: ((id: string, res: OutJSON) => void) | null = null;
    private globalDisconnectCallback: ((id: string, res: OutJSON) => void) | null = null;

    // 创建新连接
    createConnection(id: string, config: ConnectionConfig): boolean {
        if (this.connections.has(id)) {
            console.warn("zslTcp", `Connection with id ${id} already exists`);
            return false;
        }

        const client = new ConcreteTcpClient(id, {
            ...config,
            onReceiveCallback: (id, res) => {
                // 先调用连接特定的回调
                config.onReceiveCallback?.(id, res);
                // 再调用全局回调
                this.globalReceiveCallback?.(id, res);
            },
            onConnectCallback: config.onConnectCallback,
            onDisconnectCallback: (id, res) => {
                // 先调用连接特定的回调
                config.onDisconnectCallback?.(id, res);
                // 再调用全局回调
                this.globalDisconnectCallback?.(id, res);
                // 连接断开后从管理器中移除
                this.connections.delete(id);
            }
        });

        this.connections.set(id, client);
        return true;
    }

    // 获取连接
    getConnection(id: string): ConcreteTcpClient | null {
        return this.connections.get(id) || null;
    }

    // 移除连接
    removeConnection(id: string): boolean {
        const client = this.connections.get(id);
        if (client) {
            if (client.isConnected()) {
                client.disconnect();
            }
            this.connections.delete(id);
            return true;
        }
        return false;
    }

    // 获取所有连接
    getAllConnections(): Map<string, ConcreteTcpClient> {
        return this.connections;
    }

    // 设置全局接收回调
    setGlobalReceiveCallback(callback: (id: string, res: OutJSON) => void): void {
        this.globalReceiveCallback = callback;
    }

    // 设置全局断开连接回调
    setGlobalDisconnectCallback(callback: (id: string, res: OutJSON) => void): void {
        this.globalDisconnectCallback = callback;
    }

    // 断开所有连接
    disconnectAll(): void {
        this.connections.forEach((client, id) => {
            if (client.isConnected()) {
                client.disconnect();
            }
        });
        this.connections.clear();
    }
}

// 创建连接管理器实例
const connectionManager = new TcpConnectionManager();

export default class zslTcp {
    constructor() {
        this.registerAppLifecycle();
    }

    registerAppLifecycle() {
        UTSAndroid.onAppActivityDestroy(() => {
            console.log("zslTcp", "app销毁,断开所有TCP连接");
            connectionManager.disconnectAll();
        });
    }

    // 创建连接
    createConnection(jsonObject: UTSJSONObject, callback: (res: OutJSON) => void): boolean {
        const id = jsonObject.id as string;
        const ip = jsonObject.ip as string;
        const port = jsonObject.port as number;

        return connectionManager.createConnection(id, {
            id,
            ip,
            port,
            onConnectCallback: (connId, res) => {
                callback(res);
            }
        });
    }

    // 连接方法
    connect(jsonObject: UTSJSONObject, callback: (res: OutJSON) => void): boolean {
        const id = jsonObject.id as string;
        const client = connectionManager.getConnection(id);

        if (!client) {
            const outJson: OutJSON = {
                code: 0,
                msg: "Connection not found",
                data: ""
            };
            callback(outJson);
            return false;
        }

        const ip = jsonObject.ip as string || client.config.ip;
        const port = jsonObject.port as number || client.config.port;

        // 更新配置
        client.config.onConnectCallback = (connId, res) => {
            callback(res);
        };

        client.connect(ip, port);
        return true;
    }

    // 断开指定连接
    disconnect(jsonObject: UTSJSONObject): boolean {
        const id = jsonObject.id as string;
        return connectionManager.removeConnection(id);
    }

    // 断开所有连接
    disconnectAll(): void {
        connectionManager.disconnectAll();
    }

    // 检查连接状态
    isConnected(jsonObject: UTSJSONObject, jsCallback: (res: boolean) => void): void {
        const id = jsonObject.id as string;
        const client = connectionManager.getConnection(id);
        if (client) {
            jsCallback(client.isConnected());
        } else {
            jsCallback(false);
        }
    }

    // 发送字符串
    sendStr(jsonObject: UTSJSONObject): boolean {
        const id = jsonObject.id as string;
        const msg = jsonObject.message as string;
        const client = connectionManager.getConnection(id);

        if (client) {
            const transceiver = client.getTransceiver();
            if (transceiver != null) {
                return transceiver.send(msg);
            }
        }
        return false;
    }

    // 发送十六进制字符串
    sendHexStr(jsonObject: UTSJSONObject): boolean {
        const id = jsonObject.id as string;
        const msg = jsonObject.message as string;
        const client = connectionManager.getConnection(id);

        if (client) {
            const transceiver = client.getTransceiver();
            if (transceiver != null) {
                return transceiver.sendHexStr(msg);
            }
        }
        return false;
    }

    // 设置接收回调(针对特定连接)
    onReceive(jsonObject: UTSJSONObject, callback: (res: OutJSON) => void): void {
        const id = jsonObject.id as string;
        const client = connectionManager.getConnection(id);

        if (client) {
            client.config.onReceiveCallback = (connId, res) => {
                callback(res);
            };
        }
    }

    // 设置全局接收回调(所有连接)
    onGlobalReceive(callback: (id: string, res: OutJSON) => void): void {
        connectionManager.setGlobalReceiveCallback(callback);
    }

    // 设置断开连接回调(针对特定连接)
    onDisconnect(jsonObject: UTSJSONObject, callback: (res: OutJSON) => void): void {
        const id = jsonObject.id as string;
        const client = connectionManager.getConnection(id);

        if (client) {
            client.config.onDisconnectCallback = (connId, res) => {
                callback(res);
            };
        }
    }

    // 设置全局断开连接回调(所有连接)
    onGlobalDisconnect(callback: (id: string, res: OutJSON) => void): void {
        connectionManager.setGlobalDisconnectCallback(callback);
    }

    // 获取所有连接ID
    getAllConnectionIds(callback: (ids: string[]) => void): void {
        const ids = Array.from(connectionManager.getAllConnections().keys());
        callback(ids);
    }

    // 移除连接(不断开,只是从管理器移除)
    removeConnection(jsonObject: UTSJSONObject): boolean {
        const id = jsonObject.id as string;
        return connectionManager.removeConnection(id);
    }
}

使用示例

// 创建TCP连接实例
const tcpManager = new zslTcp();

// 创建连接配置
const config = {
    id: "connection_1",
    ip: "192.168.1.100",
    port: 8080
};

// 创建连接
tcpManager.createConnection(config, (res) => {
    console.log("创建连接结果:", res);
});

// 连接到服务器
tcpManager.connect(config, (res) => {
    console.log("连接结果:", res);
});

// 发送数据
tcpManager.sendStr({
    id: "connection_1",
    message: "Hello Server"
});

// 设置接收回调
tcpManager.onReceive({id: "connection_1"}, (res) => {
    console.log("收到数据:", res);
});

// 创建第二个连接
tcpManager.createConnection({
    id: "connection_2",
    ip: "192.168.1.101",
    port: 8080
}, (res) => {
    console.log("创建第二个连接结果:", res);
});

隐私、权限声明

1. 本插件需要申请的系统权限列表:

<uses-permission android:name="android.permission.INTERNET"/>

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

插件不采集任何数据

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议

暂无用户评论。