/**
   * Receives the bytes that have been sent over the connection, constructs a <code>Message</code>
   * object, and returns it.
   *
   * <p>If there are no <code>Message</code>s waiting on the connection, this method will block
   * until a message is received, or the <code>MessageConnection</code> is closed.
   *
   * @return a <code>Message</code> object
   * @exception IOException if an I/O error occurs.
   */
  public synchronized Message receive() throws IOException {

    dgc.receive(mess);

    /* get message buffer and extract info */
    byte[] buf = mess.getData();
    SMSPacket packet = new SMSPacket(buf);
    int msgType = packet.getEncodingType();
    int smsPort = packet.getPort();
    long time = packet.getTimeStamp();
    String address = packet.getAddress();
    String phoneNumber = packet.getPhoneNumber();
    int msgLen = packet.getMessageLength();
    byte[] messg = packet.getMessage(msgLen);

    debug("SMS PACKET: encodingType = " + msgType);
    debug("SMS PACKET: port = " + smsPort);
    debug("SMS PACKET: time = " + time);
    debug("SMS PACKET: address = " + address);
    debug("SMS PACKET: Sender's phone number = " + phoneNumber);
    debug("SMS PACKET: message length = " + msgLen);
    debug("SMS PACKET: message:" + new String(messg));

    Message msg = null;
    if (msgType == MessageTransportConstants.GSM_TEXT
        || msgType == MessageTransportConstants.GSM_UCS2) {

      TextMessage textmsg = (TextMessage) newMessage(MessageConnection.TEXT_MESSAGE, address);

      /* Always store text messages as UCS 2 bytes. */
      if (msgType == MessageTransportConstants.GSM_TEXT) {
        messg = TextEncoder.decode(messg);
      }
      ((TextObject) textmsg).setPayloadData(messg);
      msg = textmsg;
    } else {
      BinaryMessage binmsg = (BinaryMessage) newMessage(MessageConnection.BINARY_MESSAGE, address);
      ((BinaryObject) binmsg).setPayloadData(messg);
      msg = binmsg;
    }
    ((MessageObject) msg).setTimeStamp(time);

    return msg;
  }