Exemple #1
1
  static void toHexString(String header, ByteBuffer buf) {
    sb.delete(0, sb.length());

    for (int index = 0; index < buf.limit(); index++) {
      String hex = Integer.toHexString(0x0100 + (buf.get(index) & 0x00FF)).substring(1);
      sb.append((hex.length() < 2 ? "0" : "") + hex + " ");
    }
    LOG.debug(
        "hex->"
            + header
            + ": position,limit,capacity "
            + buf.position()
            + ","
            + buf.limit()
            + ","
            + buf.capacity());
    LOG.debug("hex->" + sb.toString());
  }
 private void recv(SocketChannel sc, ClientInfo ci) throws IOException {
   ci.channel.read(ci.inBuf);
   ByteBuffer tmpBuf = ci.inBuf.duplicate();
   tmpBuf.flip();
   int bytesProcessed = 0;
   boolean doneLoop = false;
   while (!doneLoop) {
     byte b;
     try {
       b = tmpBuf.get();
     } catch (BufferUnderflowException bue) {
       // Processed all data in buffer
       ci.inBuf.clear();
       doneLoop = true;
       break;
     }
     switch (b) {
       case TypeServerConstants.WELCOME:
         bytesProcessed++;
         break;
       case TypeServerConstants.GET_STRING_REQUEST:
         bytesProcessed++;
         if (ci.outputPending) {
           // Client is backed up. We can't append to
           // the byte buffer because it's in the wrong
           // state. We could allocate another buffer
           // here and change our send method to know
           // about multiple buffers, but we'll just
           // assume that the client is dead
           break;
         }
         ci.outBuf.put(TypeServerConstants.GET_STRING_RESPONSE);
         ByteBuffer strBuf = encoder.encode(testString);
         ci.outBuf.putShort((short) strBuf.remaining());
         ci.outBuf.put(strBuf);
         ci.outBuf.flip();
         send(sc, ci);
         break;
       case TypeServerConstants.GET_STRING_RESPONSE:
         int startPos = tmpBuf.position();
         try {
           int nBytes = tmpBuf.getInt();
           byte[] buf = new byte[nBytes];
           tmpBuf.get(buf);
           bytesProcessed += buf.length + 5;
           String s = new String(buf);
           // Send the string to the GUI
           break;
         } catch (BufferUnderflowException bue) {
           // Processed all available data
           ci.inBuf.position(ci.inBuf.position() + bytesProcessed);
           doneLoop = true;
         }
         break;
     }
   }
 }
Exemple #3
0
 static byte[] extractByteString(ByteBuffer buf) {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len];
     buf.get(str, 0, len);
     buf.get(); // trailing null
   } else str = new byte[0];
   return str;
 }
Exemple #4
0
 static String extractString(ByteBuffer buf) throws java.io.UnsupportedEncodingException {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len - 1];
     ;
     buf.get(str, 0, len - 1);
     buf.get(); // trailing null
   } else str = new byte[0];
   return new String(str, "UTF-8");
 }
Exemple #5
0
 static byte[] extractByteArray(ByteBuffer buf) {
   int len = buf.getInt();
   if (len > 0) {
     byte[] a = new byte[len];
     buf.get(a, 0, len);
     return a;
   } else return new byte[0];
 }
Exemple #6
0
 public static byte[] getNBOPort(short p) {
   ByteBuffer buf = ByteBuffer.allocate(2);
   buf.putShort((short) p);
   buf.order(ByteOrder.BIG_ENDIAN);
   buf.rewind();
   byte[] rtn = new byte[2];
   buf.get(rtn);
   return rtn;
 }
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
  public static void main(String[] args) {
    try {
      System.out.println("CliTest.java");
      // create TCP socket channel
      SocketChannel channel = SocketChannel.open();
      System.out.println("CliTest.java: channel created");
      channel.connect(new InetSocketAddress("localhost", PORT));
      System.out.println("CliTest.java: channel socket connected");
      System.out.println();

      // create  & send a login message
      byte[] bytes = LoginMessage.getLoginMessage("user1", "password1");
      System.out.println("CliTest.java: login message created");
      System.out.println(LoginMessage.getMessageString(bytes));
      System.out.printf("CliTest.java: login message length in bytes: %d\n", bytes.length);
      ByteBuffer buf = ByteBuffer.allocate(4096);
      buf.put(bytes);
      buf.flip();
      // System.out.printf("CliTest.java: buf.remaining before channel.write(): %d\n",
      // buf.remaining());
      int numwritten = channel.write(buf);
      System.out.printf(
          "CliTest.java: login mesage written: number of bytes written: %d\n", numwritten);

      // read reply message
      buf.clear();
      int numread = channel.read(buf);
      bytes = new byte[numread];
      buf.flip();
      buf.get(bytes);
      if (LoginMessage.isLoginSuccessMessage(bytes)) {
        System.out.printf(
            "CliTest.java: first message read: Success Message: number of bytes read: %d\n",
            numread);
        // get remote port number from success message
        int port = LoginMessage.getPort(bytes);
        System.out.printf("Port Number: %d\n", port);
        byte playerid = LoginMessage.getPlayerId(bytes);
        System.out.printf("Player id: %d\n", playerid);
        String mcastString = LoginMessage.getMulticastAddress(bytes);
        System.out.printf("Multicast Address: %s\n", mcastString);
        // create datagram channel & connect to rem port
        DatagramChannel dchannel = DatagramChannel.open();
        dchannel.socket().bind(new InetSocketAddress(0));
        dchannel.socket().connect(new InetSocketAddress(channel.socket().getInetAddress(), port));
        // get localport of datagram socket
        int localport = dchannel.socket().getLocalPort();
        System.out.printf("UDP local port: %d\n", localport);
        // send success message to send port number to server
        bytes = LoginMessage.getLoginSuccessMessage(playerid, null, localport);
        buf.clear();
        buf.put(bytes);
        buf.flip();
        channel.write(buf);

        DeathMessage dm = new DeathMessage((byte) 1, (byte) 1);
        bytes = dm.getByteMessage();
        buf.clear();
        buf.put(bytes);
        buf.flip();
        channel.write(buf);
      } else {
        System.out.printf(
            "CliTest.java: first message read: NOT Success Message: number of bytes read: %d\n",
            numread);
      }
      channel.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Handles control packet.
   *
   * @param data raw packet data that arrived on control PPID.
   * @param sid SCTP stream id on which the data has arrived.
   */
  private synchronized void onCtrlPacket(byte[] data, int sid) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(data);
    int messageType = /* 1 byte unsigned integer */ 0xFF & buffer.get();

    if (messageType == MSG_CHANNEL_ACK) {
      if (logger.isDebugEnabled()) {
        logger.debug(getEndpoint().getID() + " ACK received SID: " + sid);
      }
      // Open channel ACK
      WebRtcDataStream channel = channels.get(sid);
      if (channel != null) {
        // Ack check prevents from firing multiple notifications
        // if we get more than one ACKs (by mistake/bug).
        if (!channel.isAcknowledged()) {
          channel.ackReceived();
          notifyChannelOpened(channel);
        } else {
          logger.warn("Redundant ACK received for SID: " + sid);
        }
      } else {
        logger.error("No channel exists on sid: " + sid);
      }
    } else if (messageType == MSG_OPEN_CHANNEL) {
      int channelType = /* 1 byte unsigned integer */ 0xFF & buffer.get();
      int priority = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      long reliability = /* 4 bytes unsigned integer */ 0xFFFFFFFFL & buffer.getInt();
      int labelLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      int protocolLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      String label;
      String protocol;

      if (labelLength == 0) {
        label = "";
      } else {
        byte[] labelBytes = new byte[labelLength];

        buffer.get(labelBytes);
        label = new String(labelBytes, "UTF-8");
      }
      if (protocolLength == 0) {
        protocol = "";
      } else {
        byte[] protocolBytes = new byte[protocolLength];

        buffer.get(protocolBytes);
        protocol = new String(protocolBytes, "UTF-8");
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            "!!! "
                + getEndpoint().getID()
                + " data channel open request on SID: "
                + sid
                + " type: "
                + channelType
                + " prio: "
                + priority
                + " reliab: "
                + reliability
                + " label: "
                + label
                + " proto: "
                + protocol);
      }

      if (channels.containsKey(sid)) {
        logger.error("Channel on sid: " + sid + " already exists");
      }

      WebRtcDataStream newChannel = new WebRtcDataStream(sctpSocket, sid, label, true);
      channels.put(sid, newChannel);

      sendOpenChannelAck(sid);

      notifyChannelOpened(newChannel);
    } else {
      logger.error("Unexpected ctrl msg type: " + messageType);
    }
  }
 private void readMessage(SelectionKey sk, SocketChannel readChannel, TcpAddress incomingAddress)
     throws IOException {
   // note that socket has been used
   SocketEntry entry = (SocketEntry) sockets.get(incomingAddress);
   if (entry != null) {
     entry.used();
     ByteBuffer readBuffer = entry.getReadBuffer();
     if (readBuffer != null) {
       readChannel.read(readBuffer);
       if (readBuffer.hasRemaining()) {
         readChannel.register(selector, SelectionKey.OP_READ, entry);
       } else {
         dispatchMessage(incomingAddress, readBuffer, readBuffer.capacity());
       }
       return;
     }
   }
   ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
   byteBuffer.limit(messageLengthDecoder.getMinHeaderLength());
   long bytesRead = readChannel.read(byteBuffer);
   if (logger.isDebugEnabled()) {
     logger.debug("Reading header " + bytesRead + " bytes from " + incomingAddress);
   }
   MessageLength messageLength = new MessageLength(0, Integer.MIN_VALUE);
   if (bytesRead == messageLengthDecoder.getMinHeaderLength()) {
     messageLength = messageLengthDecoder.getMessageLength(ByteBuffer.wrap(buf));
     if (logger.isDebugEnabled()) {
       logger.debug("Message length is " + messageLength);
     }
     if ((messageLength.getMessageLength() > getMaxInboundMessageSize())
         || (messageLength.getMessageLength() <= 0)) {
       logger.error(
           "Received message length "
               + messageLength
               + " is greater than inboundBufferSize "
               + getMaxInboundMessageSize());
       synchronized (entry) {
         entry.getSocket().close();
         logger.info("Socket to " + entry.getPeerAddress() + " closed due to an error");
       }
     } else {
       byteBuffer.limit(messageLength.getMessageLength());
       bytesRead += readChannel.read(byteBuffer);
       if (bytesRead == messageLength.getMessageLength()) {
         dispatchMessage(incomingAddress, byteBuffer, bytesRead);
       } else {
         byte[] message = new byte[byteBuffer.limit()];
         byteBuffer.flip();
         byteBuffer.get(message, 0, byteBuffer.limit() - byteBuffer.remaining());
         entry.setReadBuffer(ByteBuffer.wrap(message));
       }
       readChannel.register(selector, SelectionKey.OP_READ, entry);
     }
   } else if (bytesRead < 0) {
     logger.debug("Socket closed remotely");
     sk.cancel();
     readChannel.close();
     TransportStateEvent e =
         new TransportStateEvent(
             DefaultTcpTransportMapping.this,
             incomingAddress,
             TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
             null);
     fireConnectionStateChanged(e);
   }
 }