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

java 复制代码
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:

相关推荐
多多*3 小时前
分布式系统中的CAP理论和BASE理论
java·数据结构·算法·log4j·maven
sg_knight3 小时前
Docker 实战:如何限制容器的内存使用大小
java·spring boot·spring·spring cloud·docker·容器·eureka
合作小小程序员小小店4 小时前
web网页开发,在线考勤管理系统,基于Idea,html,css,vue,java,springboot,mysql
java·前端·vue.js·后端·intellij-idea·springboot
随便叫个啥呢5 小时前
java使用poi-tl模版+vform自定义表单生成word,使用LibreOffice导出为pdf
java·pdf·word
面向星辰6 小时前
扣子开始节点和结束节点
java·服务器·前端
烤麻辣烫7 小时前
黑马程序员苍穹外卖(新手)Day1
java·数据库·spring boot·学习·mybatis
失散137 小时前
分布式专题——51 ES 深度分页问题及其解决方案详解
java·分布式·elasticsearch·架构
FreeBuf_7 小时前
思科CCX软件曝高危RCE:攻击者可利用Java RMI和CCX Editor获取root权限
java·网络·安全
_esther_7 小时前
【字符串String类大集合】构造创建_常量池情况_获取方法_截取方法_转换方法_String和基本数据类型互转方法
java