You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不同机器的Java Jar包间传输数据(如boolean值)

嘿,针对你要跨机器实时传递Java Jar里boolean值的需求,我给你整理几个实用的方案,都是比SQL更适合实时场景的:

1. 基于Socket的直接通信(轻量实时首选)

这是最基础的点对点通信方式,不需要任何中间件,直接在两个Jar之间建立TCP连接,实时性极强。适合简单的一对一交互场景。

举个极简的实现例子:
服务端Jar(接收值):

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BooleanReceiver {
    public static void main(String[] args) throws Exception {
        // 监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待发送端连接...");
        Socket clientSocket = serverSocket.accept();
        
        // 读取boolean值(Java的boolean在流里占1字节)
        DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
        boolean receivedValue = inputStream.readBoolean();
        System.out.println("收到的boolean值:" + receivedValue);
        
        // 关闭资源
        inputStream.close();
        clientSocket.close();
        serverSocket.close();
    }
}

客户端Jar(发送值):

import java.io.DataOutputStream;
import java.net.Socket;

public class BooleanSender {
    public static void main(String[] args) throws Exception {
        // 连接目标机器的8888端口,替换成实际IP
        Socket socket = new Socket("192.168.1.100", 8888);
        
        // 发送boolean值
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        boolean sendValue = true; // 你要发送的布尔值
        outputStream.writeBoolean(sendValue);
        System.out.println("已发送值:" + sendValue);
        
        // 关闭资源
        outputStream.flush();
        outputStream.close();
        socket.close();
    }
}

优点:轻量无依赖、实时性拉满;缺点:需要自己处理连接断开重连、多客户端接入等问题,适合简单场景。

2. 使用消息队列MQ(复杂场景推荐)

如果你的业务后续可能扩展(比如多机器交互、传递更多类型数据),消息队列是更稳妥的选择,比如RabbitMQ、Kafka这类,天然支持异步实时通信,还能解耦发送方和接收方。

以RabbitMQ为例,简单实现步骤:

  1. 两个Jar都引入RabbitMQ的Java客户端依赖
  2. 发送端Jar把boolean值序列化后发送到队列
  3. 接收端Jar监听队列,实时收到消息就处理

发送端代码:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class MQBooleanSender {
    private static final String QUEUE_NAME = "boolean_data_queue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("你的MQ服务器IP"); // 可以是其中一台机器的IP,单独部署也行
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            boolean sendValue = false;
            // 把boolean转成字节数组发送(也可以用JSON序列化)
            byte[] message = new byte[]{(byte) (sendValue ? 1 : 0)};
            channel.basicPublish("", QUEUE_NAME, null, message);
            System.out.println("已发送布尔值到队列:" + sendValue);
        }
    }
}

接收端代码:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class MQBooleanReceiver {
    private static final String QUEUE_NAME = "boolean_data_queue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("你的MQ服务器IP");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println("等待接收队列消息...");

        // 回调处理收到的消息
        DeliverCallback callback = (tag, delivery) -> {
            byte[] messageBytes = delivery.getBody();
            boolean receivedValue = messageBytes[0] == 1;
            System.out.println("从队列收到布尔值:" + receivedValue);
        };
        channel.basicConsume(QUEUE_NAME, true, callback, tag -> {});
    }
}

优点:解耦发送方和接收方、支持多生产者多消费者、自带消息持久化(防止丢消息);缺点:需要部署MQ中间件,学习成本略高,但长期来看扩展性最好。

3. 基于HTTP接口(快速上手首选)

如果不想折腾Socket或MQ,用HTTP接口也能实现实时传值,开发成本极低,调试也方便,适合快速验证需求。可以用Spring Boot快速搭服务,或者直接用JDK自带的HttpServer。

服务端Jar(接收值):

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class HttpBooleanReceiver {
    public static void main(String[] args) throws IOException {
        // 启动8080端口的HTTP服务
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/receiveBoolean", new BooleanHandler());
        server.setExecutor(null); // 使用默认线程池
        server.start();
        System.out.println("HTTP接收服务启动在8080端口");
    }

    static class BooleanHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) {
                // 读取请求体中的布尔值(这里简单处理为true/false字符串)
                String requestBody = new String(exchange.getRequestBody().readAllBytes());
                boolean receivedValue = Boolean.parseBoolean(requestBody);
                System.out.println("收到HTTP请求的布尔值:" + receivedValue);

                // 返回响应
                String response = "接收成功";
                exchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
    }
}

客户端Jar(发送值):

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpBooleanSender {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        boolean sendValue = true;
        // 发送POST请求到目标机器的接口
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://192.168.1.100:8080/receiveBoolean"))
                .POST(HttpRequest.BodyPublishers.ofString(String.valueOf(sendValue)))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("服务端响应:" + response.body());
    }
}

优点:开发简单、无需额外中间件、调试方便;缺点:实时性比Socket和MQ稍差,但普通场景完全够用。


内容的提问来源于stack exchange,提问作者AZ Games

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:08:45