第 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 端口) |