Windows下Java连接Sumo 1.14.0 TCP无法发命令,求升级示例
Java通过TCP连接Sumo 1.14.0执行TraCI命令示例
Sumo 1.14.0的TraCI协议相比旧版本有细节调整,旧代码失效大概率是协议版本不匹配或命令格式未遵循新版规范。以下是直接通过TCP收发TraCI命令的Java实现示例,涵盖连接建立、仿真步执行、响应处理核心流程:
核心代码实现
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class SumoTraCIConnector { private Socket traciSocket; private DataOutputStream out; private DataInputStream in; // Sumo 1.14.0对应的TraCI协议版本 private static final int TRACI_PROTOCOL_VERSION = 18; public void connect(String host, int port) throws IOException { traciSocket = new Socket(host, port); out = new DataOutputStream(traciSocket.getOutputStream()); in = new DataInputStream(traciSocket.getInputStream()); // 发送初始化命令:设置协议版本 sendInitCommand(); // 读取初始化响应,确认连接成功 readInitResponse(); System.out.println("已成功连接到Sumo并完成TraCI协议握手"); } private void sendInitCommand() throws IOException { // TraCI命令结构:命令ID(1字节) + 数据长度(4字节) + 协议版本(4字节) out.writeByte(0x00); // INIT命令ID out.writeInt(4); // 后续数据长度(协议版本占4字节) out.writeInt(TRACI_PROTOCOL_VERSION); out.flush(); } private void readInitResponse() throws IOException { // 响应结构:状态码(1字节) + 数据长度(4字节) + 协议版本(4字节) byte status = in.readByte(); int length = in.readInt(); int serverVersion = in.readInt(); if (status != 0x00) { throw new IOException("TraCI初始化失败,状态码:" + status); } if (serverVersion != TRACI_PROTOCOL_VERSION) { System.err.println("警告:协议版本不匹配,客户端版本:" + TRACI_PROTOCOL_VERSION + ",服务端版本:" + serverVersion); } } public void executeSimulationStep(double stepLength) throws IOException { // 发送仿真步进命令 out.writeByte(0x02); // SIMULATION_STEP命令ID // 数据长度:double类型占8字节 out.writeInt(8); out.writeDouble(stepLength); out.flush(); // 读取步进响应 byte status = in.readByte(); int length = in.readInt(); // 步进响应无额外数据,读取空内容 in.skipBytes(length); if (status != 0x00) { throw new IOException("仿真步进执行失败,状态码:" + status); } System.out.println("完成一次仿真步,步长:" + stepLength); } public void disconnect() throws IOException { // 发送关闭连接命令 out.writeByte(0x01); // CLOSE命令ID out.writeInt(0); // 无数据 out.flush(); // 关闭流和socket in.close(); out.close(); traciSocket.close(); System.out.println("已断开与Sumo的连接"); } public static void main(String[] args) { SumoTraCIConnector connector = new SumoTraCIConnector(); try { // 连接本地Sumo的TraCI端口(默认8813) connector.connect("localhost", 8813); // 执行10次仿真步,每次步长1秒 for (int i = 0; i < 10; i++) { connector.executeSimulationStep(1.0); Thread.sleep(1000); // 模拟实时间隔,可选 } } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { try { connector.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } }
运行说明
- 启动Sumo时必须开启TraCI远程端口:
sumo -c your_simulation_config.sumocfg --remote-port 8813 - 确保Java代码运行时,Sumo已处于运行状态且端口未被占用
- 若需要执行其他TraCI命令(如获取车辆状态、设置信号灯),只需按照对应命令ID和参数格式扩展方法即可,参考Sumo 1.14.0的TraCI协议文档规范参数结构
内容的提问来源于stack exchange,提问作者mahyar sadeghi
相关产品推荐
相关产品推荐

