【Java 工具类】Java通过 TCP/IP 调用斑马打印机(完整实现)

目的:

用于通过TCP连接向斑马打印机发送ZPL指令。该类提供了静态方法sendZplCommand,封装了建立TCP连接、发送ZPL指令和异常处理功能。方法参数包括打印机IP、端口和ZPL指令字符串,返回布尔值表示打印结果。使用Hutool工具类进行资源关闭,并设置5秒超时。文末提供了ZPL在线预览工具链接,方便开发者调试。

package org.jeecg.modules.utils;


import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

/**
 * @Description: ZebraDesigner 斑马打印机 工具类
 * @Author: Wang Yuhuang
 * @Date: 2025-10-24
 * @Version: V1.0
 */
@Slf4j
public class ZebraDesignerUtil {

    // 打印机配置
    private static final String PRINTER_IP = "192.168.xx.xx";
    private static final int PRINTER_PORT = 9100;
    private static final int TIMEOUT_MS = 5000; // 5秒超时

    /**
     * 向斑马打印机发送ZPL命令
     *
     * @param printerIp  打印机IP地址
     * @param port       端口号(通常是9100)
     * @param zplCommand ZPL指令字符串
     */
    public static boolean sendZplCommand(String printerIp, int port, String zplCommand) {
        Socket socket = null;
        OutputStream out = null;
        try {
            // 建立TCP连接
            socket = new Socket();
            socket.connect(new InetSocketAddress(printerIp, port), TIMEOUT_MS);
            // 获取输出流
            out = socket.getOutputStream();
            // 发送ZPL命令
            byte[] command = zplCommand.getBytes(StandardCharsets.UTF_8);
            out.write(command);
            out.flush();
            return true;
        } catch (SocketTimeoutException e) {
            log.error("连接打印机超时 ({}ms): {}:{}", TIMEOUT_MS, printerIp, port, e);
            return false;
        } catch (IOException e) {
            log.error("打印失败! 打印机地址: {}:{}, 错误: {}", printerIp, port, e.getMessage(), e);
            return false;
        } finally {
            // Hutool 关闭资源
            IoUtil.close(out);
            IoUtil.close(socket);
        }
    }

    public static void main(String[] args) {
        // ZPL指令:打印一行文字
        String zplData = "^XA\n" +
                "^FX Third section with bar code.\n" +
                "^BY5,2,270\n" +
                "^FO100,550^BC^FD12345678^FS\n" +
                "^XZ";
        //发送指令
        boolean success = sendZplCommand(PRINTER_IP, PRINTER_PORT, zplData);
    }

}

ZPL:

  • 在线 ZPL 预览工具:https://labelary.com/viewer.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不懂英语的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值