簡體   English   中英

Java服務器套接字發送多個消息的問題

[英]Java server socket sending multiple messages issue

我們有一個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="";
       }   
      }
   }
}

如果您的設備正在對每條消息發送ACK,並且服務器能夠接收到該消息,則可以按照以下方式處理服務器端程序。
編輯
我已經根據需求分析更新了代碼。 讓我知道實施后是否發現任何差異。

Thread.sleep(1000)不是上述情況的可靠解決方案,因為我們不知道設備執行Server之前發送的命令可能需要多長時間。

    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;
       }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM