第 5 章 WebSocket プロトコルと JS SDK

Last Updated: 2026-10-25 02:56 Views: 7

第 5 章 WebSocket プロトコルと JS SDK

5.1 接続と認証

ws://127.0.0.1:8899/ws?token=T        # plain
wss://host:8898/ws?token=T            # TLS (required when the page is https)
  • 1 メッセージ = 1 送信:テンプレートとデータ(またはデータ URL)を直接渡すと、サーバーが受け付けてレンダリングし印刷します。ワイヤープロトコルにメソッドのエンベロープはありません。
  • 照会(プリンター/テンプレート/ジョブ詳細/キャンセル)は常に REST を使います。WS が運ぶのは送信とイベントだけです。
  • ハートビートはプロトコルレベルの ping/pong フレームを使います(ブラウザーは自動応答)。
  • 再接続:再接続後、処理中のジョブは REST GET /api/jobs/{id} で照会します(イベントは再生されません)。キャンセルも REST 経由です。

5.2 送信メッセージ(クライアント → サーバー)

フィールド 型 必須 説明
type string ✓ "print"(用紙へ)または "preview"(レンダリングのみ)
request_id string ✓ クライアント生成。accepted/done/error の対応付けに使用
template string | object ✓ REST と同じ:id / {url} / インラインオブジェクト
data any | object ✓ REST と同じ:インライン(配列 = バッチ)/ {json}/{path} / {url,headers,timeout_s}
printer string プリンター名(省略 = システムデフォルト)
copies / copies_per_record / collate / pages REST /api/print と同じ
options object REST と同じ

type:"preview" は REST POST /api/print の "preview": true と等価です。完了するとトレイがネイティブプレビューウィンドウをポップアップ表示します(9.3 節)。トレイがない環境では Web コンポーネント /preview/{job_id} を使います。

{ "type": "print", "request_id": "r1",
  "template": "sf-waybill-100x93",
  "data": { "url": "https://erp.example.com/api/waybill/12345" },
  "printer": "HP-LaserJet-M1005", "copies_per_record": 3 }

5.3 イベントメッセージ(サーバー → クライアント)

type トリガー 主なフィールド
accepted 送信が受理された request_id, job_id, total_pages
job ジョブの状態変化/進捗 job_id, status, page_done, total_pages(ブロードキャスト)
printer プリンターの状態変化 name, state(ブロードキャスト)
done ジョブ完了 request_id, job_id, status
error 送信失敗 request_id, code, message(コードは 4.2 節と同じ)
{ "type": "accepted", "request_id": "r1", "job_id": "j_01J8…", "total_pages": 6 }
{ "type": "job", "job_id": "j_01J8…", "status": "printing", "page_done": 4, "total_pages": 6 }
{ "type": "printer", "name": "HP-LaserJet-M1005", "state": "out_of_paper" }
{ "type": "done", "request_id": "r1", "job_id": "j_01J8…", "status": "done" }
{ "type": "error", "request_id": "r1", "code": "E_RENDER", "message": "…" }

5.4 生プロトコルの使用(ブラウザー)

JS SDK(5.5 節)の利用を推奨します。生プロトコルは理解とデバッグ向けです。

const ws = new WebSocket("ws://127.0.0.1:8899/ws?token=T");
ws.onopen = () => ws.send(JSON.stringify({
  type: "print", request_id: "r1",
  template: "sf-waybill-100x93",
  data: { url: "https://erp.example.com/api/waybill/12345" },
  copies_per_record: 3 }));
ws.onmessage = (e) => {
  const m = JSON.parse(e.data);
  if (m.type === "accepted") console.log("job:", m.job_id, m.total_pages);
  if (m.type === "job")     console.log(m.status, m.page_done + "/" + m.total_pages);
  if (m.type === "done")    console.log("finished");
  if (m.type === "error")   console.error(m.code, m.message);
};

5.5 JS SDK(wxprint.js)リファレンス

サーバーは http://127.0.0.1:8899/sdk/wxprint.js(UMD/ESM)をホストし、WS プロトコルとスクリプト API をメソッドにラップします。次のように読み込みます。

<script src="http://127.0.0.1:8899/sdk/wxprint.js"></script>

コンストラクターオプション

const wp = new wxprint.WxPrint({ host: "127.0.0.1", port: 8899,
                                 tlsPort: 8898, token: "T",
                                 reconnectDelay: 2000 });
// or the factory: const wp = await wxprint.connect({ token: "T" });
オプション 型 デフォルト 説明
host string location.hostname サービスのホスト
port int 8899 平文ポート(http/ws)
tlsPort int 8898 TLS ポート(ページが https のとき自動使用)
token string null 認証トークン
reconnectDelay int 2000 再接続間隔(ms)

直接印刷メソッド(WS プロトコルのラップ)

メソッド パラメーター 戻り値 説明
connect() — Promise 接続を確立(切断後は reconnectDelay で自動再接続。オフライン中の送信はキューイングされ、再接続時にフラッシュ)
close() — — 接続を閉じる(以後再接続しない)
print(req) 5.2 節と同じフィールド Promise<{job_id, total_pages}> 用紙へ送信
preview(req) 同上 Promise プレビューを送信(完了時にトレイのウィンドウがポップアップ)
saveas(req, format) req + `“pdf” “png” “zip”`
printers() — Promise プリンター一覧(REST パススルー)
job(jobId) string Promise ジョブステータス(REST パススルー)
onJob(cb) (ev) => void this ジョブイベントを購読(状態変化 + 進捗)
onPrinter(cb) (ev) => void this プリンターイベントを購読

プログラムによる組み立て(DocBuilder、スクリプト API のラップ)

wp.document() はメソッドチェーン可能なビルダーを返します。動詞は第 6 章と 1 対 1 に対応します。

メソッド パラメーター 説明
init(taskName) string タスク名(印刷キューに表示)
pagesize(w, h, opts?) mm + {orientation, continuous} ページサイズ。h=0 で内容の高さに合わせる
loadData(data) object | array インラインデータ(配列 = バッチ)
loadJSON(textOrPath) string JSON テキストまたはサーバー側ファイルパス
loadURL(url, opts?) url + {headers, timeout_s} 実行時に取得
addText(el) / addHtml(el) / addTable(el) 要素オブジェクト フィールドは 7.5~7.7 節のとおり
addBarcode(el) / addQrcode(el) / addImage(el) 要素オブジェクト フィールドは 7.8~7.10 節のとおり
addRect(el) / addLine(el) / addChart(el) 要素オブジェクト フィールドは 7.4 節のとおり
newpage() — 強制改ページ
print(params?) {printer, copies, …} 用紙へ送信
preview() — プレビューを送信

完全な例

// ① Direct printing + event subscription
const wp = new wxprint.WxPrint({ token: "T" });
wp.onJob(ev => console.log(ev.status, ev.page_done + "/" + ev.total_pages));
wp.onPrinter(ev => console.log(ev.name, ev.state));
await wp.print({ template: "sf-waybill-100x93",
                 data: { url: "https://erp.example.com/api/waybill/12345" },
                 printer: "HP-LaserJet-M1005", copies_per_record: 3 });

// ② Programmatic building (no template file)
const doc = wp.document();
doc.init("Delivery note")
   .loadURL("https://erp.example.com/api/order/SO-1024")
   .pagesize(210, 297)
   .addText({ x: 20, y: 15, w: 80, h: 8, text: "{{title}}",
              font: { size_pt: 16, weight: 700 } })
   .addBarcode({ x: 20, y: 30, w: 60, h: 10,
                 symbology: "code128", content: "{{order_no}}" })
   .newpage()
   .addHtml({ x: 0, y: 0, w: 210, h: 297,
              html: "<table>{% for it in items %}<tr><td>{{it.name}}</td></tr>{% endfor %}</table>" });
await doc.print({ printer: "HP-LaserJet-M1005", copies: 2 });

5.6 WS か REST か?

シナリオ 推奨
Web からの送信 + 進捗/完了のライブコールバック WS(または SDK の print)
バックエンドの一発送信、必要時のステータス照会 REST + ポーリング
キャンセル/詳細照会 REST(WS は照会を運ばない)
HTTPS ページ wss(SDK は自動的に TLS ポートへ切り替え)
← Previous Article 第 4 章 HTTP API リファレンス Next Article → 第 6 章 スクリプト API リファレンス

Comments

No comments yet