【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:

相关推荐
执笔论英雄1 天前
【RL】async原理
java·服务器·前端
z***94841 天前
Java进阶07 嵌套类
java·开发语言·python
python百炼成钢1 天前
43.Linux LCD驱动
java·linux·运维·驱动开发
w***H6501 天前
Springboot项目:使用MockMvc测试get和post接口(含单个和多个请求参数场景)
java·spring boot·后端
橘子编程1 天前
仓颉语言:华为新一代编程利器
java·c语言·开发语言·数据库·python·青少年编程
a***13141 天前
Spring Boot 条件注解:@ConditionalOnProperty 完全解析
java·spring boot·后端
axihaihai1 天前
maven的构建问题
java·linux·maven
tgethe1 天前
Java注解
java·后端
稚辉君.MCA_P8_Java1 天前
DeepSeek Java 多线程打印的12种实现方法
java·linux·后端·架构·maven
代码不停1 天前
Java栈题目练习
java·开发语言