コード例 #1
0
  /** 用广播方式发送一条消息 */
  public void send(String topic, byte[] infobuf)
      throws
          UDPBaseException { // System.out.println ("Sending-----["+topic+"]["+infobuf.length+"]") ;
    // log.log("Sending-----["+topic+"]["+infobuf.length+"]") ;
    if (bInitNull) {
      return;
    }

    if (DEBUG) {
      log("UdpBase Sending--->>[" + topic + "][" + infobuf.length + "]");
    }

    if (topic.length() > 150) {
      throw new UDPBaseException("Topic is too long!!");
    }
    if (infobuf == null || infobuf.length == 0) {
      throw new UDPBaseException("Info to be send cannot null!");
    }

    try {
      String tmpid = getOneID();
      // System.out.println ("ONE ID="+tmpid) ;
      int bs = infobuf.length / MAX_PACKET_LENGTH;
      int sy = infobuf.length % MAX_PACKET_LENGTH;
      int pknum = bs + (sy == 0 ? 0 : 1);
      DatagramPacket packet = null;

      HeaderItem topicHeader = new HeaderItem(topic);
      HeaderItem idHeader = new HeaderItem(tmpid);
      byte[] tmpb = null;

      for (int i = 0; i < bs; i++) {
        // if (i>0)//循环发送信息每次发送间加间隔,以提高发送成功率
        Thread.sleep(LOOP_SEND_INTERVAL);
        // 增加顺序头
        HeaderItem orderHeader = new HeaderItem("" + pknum + "_" + i);
        tmpb =
            HeaderItem.appendHeaderItem(
                infobuf, i * MAX_PACKET_LENGTH, MAX_PACKET_LENGTH, orderHeader);
        // 增加唯一id
        tmpb = HeaderItem.appendHeaderItem(tmpb, idHeader);
        // 增加主题头
        tmpb = HeaderItem.appendHeaderItem(tmpb, topicHeader);
        packet = new DatagramPacket(tmpb, 0, tmpb.length, group, RECV_PORT);
        // System.out.println("send package");
        sendSocket.send(packet);
      }

      if (sy > 0) {
        Thread.sleep(LOOP_SEND_INTERVAL);
        // 增加顺序头
        HeaderItem orderHeader = new HeaderItem("" + pknum + "_" + bs);
        tmpb = HeaderItem.appendHeaderItem(infobuf, bs * MAX_PACKET_LENGTH, sy, orderHeader);
        // 增加唯一id
        tmpb = HeaderItem.appendHeaderItem(tmpb, idHeader);
        // 增加主题头
        tmpb = HeaderItem.appendHeaderItem(tmpb, topicHeader);
        packet = new DatagramPacket(tmpb, 0, tmpb.length, group, RECV_PORT);

        // System.out.println("send.."+new String(tmpb));
        sendSocket.send(packet);
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase send() error=\n" + e.toString());
    }
  }