第 5 章 WebSocket 協定與 JS SDK

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

第 5 章 WebSocket 協定與 JS SDK

5.1 連接與鑑權

ws://127.0.0.1:8899/ws?token=T        # 明文
wss://host:8898/ws?token=T            # TLS(页面为 https 时必须)
  • 一條訊息即一次提交:直接傳入模板與數據(或數據 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: done 後系統匣自動彈出原生預覽視窗(9.3 節);無系統匣時用網頁組件 /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("完成");
  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 });
// 或工厂直连:const wp = await wxprint.connect({ token: "T" });
參數 類型 預設 說明
host string location.hostname 伺服器主機
port int 8899 明文連接埠(http/ws)
tlsPort int 8898 TLS 連接埠(頁面為 https 時自動使用)
token string null 鑑權 token
reconnectDelay int 2000 斷線重連間隔(ms)

直連列印方法(封裝 WS 協定)

方法 參數 傳回 說明
connect() — Promise 建立連接(自動重連:斷開後按 reconnectDelay 重試;斷線期間的提交排隊,恢復後自動發出)
close() — — 關閉連接(不再重連)
print(req) 同 5.2 提交訊息欄位 Promise<{job_id, total_pages}> 提交出紙
preview(req) 同上 Promise 提交預覽(done 後系統匣彈窗)
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 章一一對應:

方法 參數 說明
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() — 提交預覽

完整範例

// ① 直连打印 + 事件订阅
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 });

// ② 程序化构建(不经模板文件)
const doc = wp.document();
doc.init("发货单")
   .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

場景 建議
網頁提交 + 即時進度/完成回呼 WS(或 SDK print)
後端語言一次性提交、按需查狀態 REST + 輪詢
需要取消/查詢詳情 REST(WS 不承載查詢)
HTTPS 頁面 wss(SDK 自動切換 TLS 連接埠)
← Previous Article 第 4 章 HTTP API 參考 Next Article → 第 6 章 命令式腳本 API 參考

Comments

No comments yet