• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wkin

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

TCP Socket send队列封装管理class

tcp消息发送,模拟队列版本


/**
 * @Author:
 * @Date: 2026.01.15
 * @Description: TCP Socket send队列封装管理class
 */

import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from '@hzw/logger';
import socket from '@ohos.net.socket';


const TAG = "SocketQueue";

export class SocketQueue {
  private tcpClient: socket.TCPSocket;
  private taskQueue: Array<string> = [];
  private isSending = false;

  //连接并初始化后的tcp连接对象
  constructor(tcp: socket.TCPSocket) {
    this.tcpClient = tcp;
  }

  // 添加发送任务到队列
  public send(data: string): void {
    this.taskQueue.push(data);
    Logger.d(TAG, "tcp send data:" + data)
    this.processQueue();
  }

  // 队列处理核心逻辑
  private processQueue(): void {
    if (this.isSending || this.taskQueue.length === 0) {
      return;
    }

    this.isSending = true;
    //移除并返回数组的第一个元素
    const currentTask = this.taskQueue.shift()!;


    let tcpSendOptions: socket.TCPSendOptions = {
      data: currentTask,
      encoding: 'utf-8',
    }

    this.tcpClient.send(tcpSendOptions, (err: BusinessError) => {
      this.isSending = false;

      if (err) {
        Logger.d(TAG, "tcp send fails ,callback:" + err + ", cmd is:" + currentTask)
      }

      // 立即处理下一个任务
      this.processQueue();
      console.info('tcp send data success');
    });
  }

  // 关闭连接时清空队列
  public close(): void {
    this.tcpClient.close((err: BusinessError) => {
      console.log('Connection closed');
    });
    this.taskQueue = [];
  }
}

posted on 2026-01-15 16:46  带头大哥d小弟  阅读(0)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3