Java服务器套接字发送多个消息问题

时间:2013-02-02 15:22:54

标签: java sockets

我们有一个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="";
       }   
      }
   }
}

1 个答案:

答案 0 :(得分:-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;
       }
   }