0

我们有一个 java 套接字程序,服务器从许多设备获取数据并且工作正常。有时服务器需要向设备发送一些命令。当它发送单个命令时,它工作正常。当它发送多个命令时,问题就来了,只有第一个是成功的。我们无法弄清楚为什么其余的都失败了。下面是显示消息如何发送的片段。我应该在发送消息后设置延迟吗?

public static void main(String[] args) {   

      new sServer7888();

   }
sServer7888() {


    try{
    final ServerSocket serverSocketConn = new ServerSocket(7888);               
    while (true){
    try{
       Socket socketConn1 = serverSocketConn.accept();
          new Thread(new ConnectionHandler(socketConn1)).start();                       
    }
    catch(Exception e){
        e.printStackTrace(System.out);
    }
       }
    } 
    catch (Exception e)     {
         e.printStackTrace(System.out);
    }

}


class ConnectionHandler implements Runnable {

  private Socket receivedSocketConn1;
    ConnectionHandler(Socket receivedSocketConn1) {
      this.receivedSocketConn1=receivedSocketConn1;
    }

    public void run() {

      while ((nextChar=readIn1.read()) != -1) {

         completeMessage += (char) nextChar;     
         if (nextChar == '*')
    {
         String[] splitResult = completeMessage .split(",");    
         String header=splitResult[0].trim().substring(0,4);

         if((header.equals("$ACK")){

          //update the message sent from the server as already acknowledge.
         }     
         else{
          //run query to find if there are any message to be sent out to the devices
          while(rsOC1.next()){
            commandText = rsOC1.getString("commandText");
            writeOut1.write(commandText);
            writeOut1.write("\r\n");
            writeOut1.flush(); 
          }

          //now process the normal message receive from the devices.
         } 
        completeMessage="";
       }   
      }
   }
}
4

1 回答 1

-1

如果您的设备在每条消息上都发送 ACK 并且服务器能够接收到它,那么您可以按照以下方式使用您的服务器端程序。
编辑
我已经根据需求分析更新了代码。让我知道在实施后是否发现任何差异。

Thread.sleep(1000)不是上述情况的可靠解决方案,因为我们不知道设备可能需要多长时间才能执行服务器发送的先前命令。

    public void run() 
    {

        int i = -1;
        ArrayList<String> list = new ArrayList<String>();
        while ((nextChar=readIn1.read()) != -1) 
        {
            boolean isCompleteMessage = readMessage(nextChar);
            if (isCompleteMessage)
            {
                String[] splitResult = completeMessage .split(",");    
                String header=splitResult[0].trim().substring(0,4);
                if((header.equals("$ACK"))
                {
                    String id = null;
                    if (i != -1)
                    {
                        id = list.get(i);
                        id = id.substring(0,id.indexOf("^"));
                    }
                    //update the message sent from the server as already acknowledge using id extracted above.
                    if ( i == 0)
                    {
                        list.remove(i);
                        if (list.size() == 0)
                        {
                            i = -1;
                        }
                        else
                        {
                            commandText = list.get(i);
                            writeOut1.write(commandText.substring((commandText.indexOf("^")) + 1));
                            writeOut1.write("\r\n");
                            writeOut1.flush(); 
                        }
                    }
                }     
                else
                {
                    //process here the normal message receive from the devices.
                    if (i == -1)
                    {
                        list = getRecords();
                        if (list.size() > 0)
                        {
                            i = 0;
                            commandText = list.get(i);
                            writeOut1.write(commandText.substring((commandText.indexOf("^")) + 1));
                            writeOut1.write("\r\n");
                            writeOut1.flush(); 
                        }
                    }
                    else 
                    {
                        commandText = list.get(i);
                        writeOut1.write(commandText.substring((commandText.indexOf("^")) + 1));
                        writeOut1.write("\r\n");
                        writeOut1.flush(); 
                    }
                } 
                completeMessage = "";
            }   
        }
   }
   public boolean readMessage(int nextChar)
   {
        completeMessage += (char)nextChar;
        if (((char)nextChar) == '*')
        {
            return true;
        }
        else
        {
            return false;
        }
   }
   //Retreive all commands from database and returns the ArrayList containing those commands.
   public ArrayList<String> getRecords()
   {
       ArrayList<String> list = new ArrayList<String>();
       Statement stat = null;
       ResultSet rsOC1 = null;
       try
       {
            stat = con.createStatement();
            rsOC1 = stat.executeQuery("Query for message retrieval from database");
            while (rsOC1.next())
            {
                String sElement = rs0C1.getString("commandID") + "^" + rs0C1.getString("commandText");
                list.add(sElement);
            }
       }
       catch (Exception ex){}
       finally
       {
           if (rs0C1 != null)
           {
               try
               {
                    rs0C1.close();   
               } catch () {}
           }
           if (stat != null)
           {
               try
               {
                    stat.close();   
               } catch () {}
           }
           return list;
       }
   }
于 2013-02-02T17:36:29.813 回答