제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        # plain
wss://host:8898/ws?token=T            # TLS (required when the page is 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"는 "preview": true를 붙인 REST POST /api/print와 동일합니다. 완료되면 트레이가 네이티브 미리보기 창을 띄웁니다(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 (broadcast)
printer 프린터 상태 변화 name, state (broadcast)
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장과 일대일로 대응합니다:

메서드 파라미터 설명
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?

시나리오 권장
웹 제출 + 실시간 진행/완료 콜백 WS(또는 SDK의 print)
백엔드 일회성 제출, 필요 시 상태 조회 REST + 폴링
취소 / 상세 조회 REST(WS는 조회를 담지 않음)
HTTPS 페이지 wss(SDK가 자동으로 TLS 포트로 전환)
← Previous Article 제4장 HTTP API 레퍼런스 Next Article → 제6장 스크립트 API 레퍼런스

Comments

No comments yet