⚫︎ 概要
talknリアルタイム通信プラットフォーム用のWebSocketクライアントライブラリです。
Socket.IO + Redux + WebWorkerを統合したリアルタイム通信ライブラリとして設計されており、 バンドルされたJSファイルとして外部配布されます。
- - リアルタイムチャット通信
 - - 投稿の送受信
 - - チャンネル管理
 - - ランキング機能
 - - WebWorkerによる非ブロッキング通信
 
⚫︎ インストール
CDN経由
<script src="//api.talkn.io"></script>
⚫︎ 基本的な使い方
1. シンプルな接続
// 基本的な接続
const client = await TalknAPI('your-server-connection');
// メッセージ投稿
await client.post('Hello, world!');
// 状態取得
const state = client.getState();
console.log('Current posts:', state.posts);2. 状態変更の監視
const client = await TalknAPI('your-server-connection');
// 状態変更を監視
const unsubscribe = client.subscribe((state) => {
  console.log('New posts:', state.posts);
  console.log('Channel info:', state.tuneCh);
  console.log('Rankings:', state.rank);
});
// 監視停止
unsubscribe();3. 詳細な設定
// 接続パラメータを指定
const params = {
  isTuneSameCh: true,    // 同一チャンネル接続許可
  isTuneMultiCh: true,   // 複数チャンネル接続許可
  isDebug: false         // デバッグモード
};
const client = await TalknAPI('your-server-connection', params);⚫︎ API リファレンス
TalknAPI(connection, params?)
Returns: Promise<ScopedTalknClient>
メインのファクトリ関数。接続を確立し、スコープされたクライアントを返します。
| パラメータ | 型 | 説明 | 
|---|---|---|
| connection | string | 接続先サーバーの識別子 | 
| params | TuneParams (optional) | 接続オプション | 
| メソッド | 説明 | 
|---|---|
getState(): ApiState | 現在の状態を取得します。 | 
post(content: string): Promise<ResponseType> | メッセージを投稿します。 | 
fetchPosts(): Promise<ResponseType> | 投稿一覧を取得します。 | 
fetchRank(): Promise<ResponseType> | ランキングデータを取得します。 | 
fetchDetail(): Promise<ResponseType> | チャンネル詳細情報を取得します。 | 
subscribe(callback: Function): () => void | 状態変更を監視します。登録解除関数を返します。 | 
⚫︎ 実装例
リアルタイムチャットアプリ
class ChatApp {
  constructor() {
    this.client = null;
    this.messageContainer = document.getElementById('messages');
    this.messageInput = document.getElementById('messageInput');
    this.sendButton = document.getElementById('sendButton');
  }
  async init(serverConnection) {
    try {
      // Talkn APIクライアント接続
      this.client = await TalknAPI(serverConnection, {
        isTuneSameCh: true,
        isTuneMultiCh: false
      });
      // 既存の投稿を取得
      await this.client.fetchPosts();
      
      // リアルタイム状態監視
      this.client.subscribe((state) => {
        this.updateMessages(state.posts);
        this.updateChannelInfo(state.tuneCh);
      });
      // 送信ボタンイベント
      this.sendButton.addEventListener('click', () => {
        this.sendMessage();
      });
      console.log('Chat app initialized successfully');
    } catch (error) {
      console.error('Failed to initialize chat app:', error);
    }
  }
  async sendMessage() {
    const content = this.messageInput.value.trim();
    if (content && this.client) {
      try {
        await this.client.post(content);
        this.messageInput.value = '';
      } catch (error) {
        console.error('Failed to send message:', error);
      }
    }
  }
}
// 使用例
const chatApp = new ChatApp();
chatApp.init('my-chat-room');