npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@unrealknight/pomelo-tsclient-websocket

v1.0.2

Published

pomelo客户端sdk的TypeScript版本

Readme

Pomelo TypeScript WebSocket 客户端

这是 Pomelo 的 TypeScript WebSocket 客户端库,提供了完整的类型安全支持和现代化的开发体验。

特性

  • 完整的 TypeScript 支持 - 提供类型安全的 API 和自动补全
  • 向后兼容 - 保持与原 JavaScript 版本相同的 API
  • 现代化构建 - 使用 TypeScript 编译器和现代打包工具
  • 更好的开发体验 - IDE 智能提示和错误检查
  • 灵活的使用方式 - 支持 ES 模块、CommonJS 和全局变量

安装

npm install @unrealknight/pomelo-tsclient-websocket

开发环境设置

# 安装依赖
npm install

# 构建 TypeScript
npm run build

# 监听模式构建
npm run dev

使用方法

基本用法

import pomelo, { PomeloConfig } from 'pomelo-tsclient-websocket';

const config: PomeloConfig = {
  host: 'localhost',
  port: 3014,
  user: {
    username: 'player1'
  },
  handshakeCallback: (userData) => {
    console.log('握手完成:', userData);
  }
};

pomelo.init(config, () => {
  console.log('连接成功!');
  
  // 发送请求
  pomelo.request('connector.entryHandler.enter', {
    username: 'player1',
    rid: 'room1'
  }, (data) => {
    console.log('响应:', data);
  });
  
  // 监听服务器推送
  pomelo.on('onChat', (data) => {
    console.log('收到消息:', data);
  });
});

类型安全的使用

import { createPomeloClient, PomeloConfig } from 'pomelo-tsclient-websocket';

// 定义响应类型
interface LoginResponse {
  code: number;
  user: {
    id: number;
    name: string;
    level: number;
  };
}

// 定义事件数据类型
interface ChatMessage {
  from: string;
  content: string;
  timestamp: number;
}

const client = createPomeloClient();

// 类型安全的请求
client.request<LoginResponse>('auth.login', {
  username: 'player1',
  password: 'secret'
}, (response) => {
  // response 自动推断为 LoginResponse 类型
  if (response.code === 200) {
    console.log(`欢迎 ${response.user.name}!`);
  }
});

// 类型安全的事件监听
client.on<ChatMessage>('onChat', (message) => {
  // message 自动推断为 ChatMessage 类型
  console.log(`${message.from}: ${message.content}`);
});

配置选项

interface PomeloConfig {
  host: string;                    // 服务器地址
  port?: number;                   // 服务器端口
  user?: Record<string, any>;      // 用户数据
  handshakeCallback?: (userData?: any) => void; // 握手回调
  encrypt?: boolean;               // 是否启用加密
  reconnect?: boolean;             // 是否自动重连
  maxReconnectAttempts?: number;   // 最大重连次数
  encode?: EncodeFunction;         // 自定义编码函数
  decode?: DecodeFunction;         // 自定义解码函数
}

事件处理

// 连接事件
client.on('connect', () => {
  console.log('已连接');
});

// 断开连接事件
client.on('disconnect', () => {
  console.log('连接断开');
});

// 重连事件
client.on('reconnect', () => {
  console.log('重新连接成功');
});

// 错误事件
client.on('error', (error) => {
  console.error('客户端错误:', error);
});

// 网络错误
client.on('io-error', (event) => {
  console.error('网络错误:', event);
});

高级用法

自定义编码解码

const config: PomeloConfig = {
  host: 'localhost',
  port: 3014,
  encode: (reqId, route, msg) => {
    // 自定义编码逻辑
    return customEncode(reqId, route, msg);
  },
  decode: (data) => {
    // 自定义解码逻辑
    return customDecode(data);
  }
};

加密通信

const config: PomeloConfig = {
  host: 'secure.gameserver.com',
  port: 443,
  encrypt: true, // 启用 RSA 加密
  user: {
    token: 'your-auth-token'
  }
};

API 参考

主要方法

  • init(config: PomeloConfig, callback?: InitCallback): void - 初始化并连接到服务器
  • request<T>(route: string, msg?: any, callback?: RequestCallback<T>): void - 发送请求
  • notify(route: string, msg?: any): void - 发送通知(无响应)
  • on<T>(route: string, callback: MessageCallback<T>): void - 监听事件
  • off(route: string, callback?: MessageCallback): void - 移除事件监听
  • disconnect(): void - 断开连接

类型定义

所有类型定义都可以从主模块导入:

import {
  IPomeloClient,
  PomeloConfig,
  MessageCallback,
  RequestCallback,
  HandshakeCallback,
  Message,
  PackageType,
  MessageType,
  ResponseCode
} from 'pomelo-tsclient-websocket';

兼容性

浏览器兼容性

  • Chrome 60+
  • Firefox 55+
  • Safari 11+
  • Edge 79+

Node.js 兼容性

  • Node.js 14.0+

迁移指南

从 JavaScript 版本迁移到 TypeScript 版本非常简单:

1. 基本迁移

// 原 JavaScript 代码
pomelo.init({
  host: 'localhost',
  port: 3014
}, function() {
  pomelo.request('test.route', {}, function(data) {
    console.log(data);
  });
});
// TypeScript 代码(完全兼容)
import pomelo from 'pomelo-tsclient-websocket';

pomelo.init({
  host: 'localhost',
  port: 3014
}, () => {
  pomelo.request('test.route', {}, (data) => {
    console.log(data);
  });
});

2. 添加类型支持

// 添加类型定义
interface TestResponse {
  success: boolean;
  message: string;
}

pomelo.request<TestResponse>('test.route', {}, (data) => {
  // data 现在有完整的类型支持
  if (data.success) {
    console.log(data.message);
  }
});

构建和发布

# 清理构建目录
npm run clean

# 构建项目
npm run build

# 发布到 npm
npm publish

构建后的文件结构:

dist/
├── index.js          # 主入口文件
├── index.d.ts        # 类型定义文件
├── core/             # 核心模块
├── types/            # 类型定义
└── utils/            # 工具函数

许可证

(薛之猫 许可证)

任何未经薛之猫许可的老咸鱼都不允许复制代码