0

我是 Java 的初学者,我正在从事一个涉及套接字和外部设备的项目。我为这些单元做了一个小型监听器,但在向设备发送消息时遇到了一些问题。

该单元有 2 条消息正在发送到服务器: 1. Heart Beat 消息女巫是十六进制的 2. 实际数据是一个字符串,如下所示:field1,field2,field3,field4

侦听器正在为每个设备打开一个新线程并等待消息。我使用 DataInputStream 接收消息,使用 DataOutputStream 发送消息。每次一个单元连接到服务器时,它都会打开一个新线程并获取心跳,从心跳中我知道什么类型的设备以及它是谁。如果设备是新设备,我将根据设备知道发送给我的 2 个唯一序列号对其进行配置,我必须将它们与数据库进行比较。

我的问题在于我向设备询问 2 个连续剧的部分。这需要很长时间,30 到 40 秒。发送命令必须在 10 秒内(在另一台 tcp 服务器上测试)。

这是那部分代码:

String [] commands = deviceDetails.getConfigCommands().split(";"); // I take the commands from a file, and looks like: command1;command2
for (int i=0; i<commands.length; i++) {
sendCommand = commands[i].getBytes(); // sendCommand is a byte[]
out.write(sendCommand);
out.flush();

loop: while (true) {
    in.read(buffer); // buffer is a byte[]
    String[] result = new String(buffer, "ASCII").split(":|="); // the response from the unit looks like: ok:commandname=code, i need the code

    if (configCounter ==2 && imei.equals("")) {
        i = 0;
        break loop;
    } else if(configCounter == 2 && simid.equals("")) {
        i = 1;
        break loop;
    }
    configCounter++;

    switch (result[1]) {
        case "IMEI":
            imei = result[2];
            break loop;

        case "SIMID":
            simid = result[2];
            break loop;
    }
}

}

在此期间,我正在等待单位的回复。但在此之前,我试图将命令发送到设备,每个命令大约需要 30-40 秒。

谁能告诉我上面的代码有什么问题?如何使 DataOutputStream 发送命令的速度快于 30-40 秒?

谢谢!

4

0 回答 0