Example #1
0
  public boolean connectionRequest(DatagramPacket aDatagramPacket) {

    if (aDatagramPacket.getSocketAddress().equals(mSocketAddress)) {

      String vXMLString = new String(aDatagramPacket.getData(), 0, aDatagramPacket.getLength());

      GraphicsManagement.getLogger()
          .debug(
              "Connection request ("
                  + ((InetSocketAddress) aDatagramPacket.getSocketAddress()).toString()
                  + "):"
                  + vXMLString);
      ConnectionRequest vConnectionRequest =
          ConnectionRequest.unmarshallXMLConnectionRequestString(vXMLString);

      if (vConnectionRequest != null) {

        mClientName = vConnectionRequest.getClientGraphicsName();

        String vAcknowlegeRequest =
            (new ConnectionAcknowlege(
                    Core.getInstance().getServerConfig().getServerName(), mClientName, true))
                .toXMLString();

        mGraphicsConnection.sendString(vAcknowlegeRequest, mSocketAddress);

        return true;
      }
    }

    return false;
  }
  private void readPacket() {
    // Create a byte array in order to receive and process packets
    byte[] rcvd = new byte[RxpSocket.MAXIMUM_SEGMENT_SIZE];
    DatagramPacket packet = new DatagramPacket(rcvd, RxpSocket.MAXIMUM_SEGMENT_SIZE);

    try {
      while (!isClosed) {
        // Receive a packet
        udpSocket.receive(packet);

        // Parse the packet
        RxpPacket rxpPacket = new RxpPacket(rcvd);
        MultiplexingKey key = new MultiplexingKey(packet.getSocketAddress(), rxpPacket.sourcePort);

        // Determine if the packet belongs to an existing connection
        if (connections.containsKey(key)) {
          RxpSocket rxpSocket = connections.get(key);
          // Existing connection, just send the packet to the
          // connection
          rxpSocket.rcvPacket(rxpPacket);

          if (rxpSocket.hasException()) {
            // If there is an error, get rid of the socket forcefully.
            connections.remove(key);

            // Note that the server application may have not
            // formally accepted the connection, so remove it too.
            unaccepted.remove(rxpSocket);
          }
        } else {
          // The packet is for a new connection. If it is not a SYN
          // packet, discard it.
          if (rxpPacket.isCorrupt() || !rxpPacket.isSyn) continue;

          // Create a new connection
          RxpSocket rxpSocket =
              new RxpSocket(
                  rxpSrcPort,
                  rxpPacket.sourcePort,
                  packet.getSocketAddress(),
                  udpSocket,
                  () -> {
                    connections.remove(key);
                  });
          rxpSocket.setWindowSize(defaultWindowSize);
          rxpSocket.rcvPacket(rxpPacket);

          connections.put(key, rxpSocket);

          // Add the connection to the list of unaccepted connections.
          unaccepted.add(rxpSocket);
        }
      }
    } catch (SocketException e) {
      // Note that when the socket is closed, this exception will be thrown. Ignore it.
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private byte[] getFullReply(DatagramPacket datagrampacket) {
    long i = MinecraftServer.aq();

    if (i < this.cacheTime + 5000L) {
      byte[] abyte = this.cachedReply.getBytes();
      byte[] abyte1 = this.getIdentityToken(datagrampacket.getSocketAddress());

      abyte[1] = abyte1[0];
      abyte[2] = abyte1[1];
      abyte[3] = abyte1[2];
      abyte[4] = abyte1[3];
      return abyte;
    } else {
      this.cacheTime = i;
      this.cachedReply.reset();
      this.cachedReply.write((int) 0);
      this.cachedReply.write(this.getIdentityToken(datagrampacket.getSocketAddress()));
      this.cachedReply.write("splitnum");
      this.cachedReply.write((int) 128);
      this.cachedReply.write((int) 0);
      this.cachedReply.write("hostname");
      this.cachedReply.write(this.localAddress);
      this.cachedReply.write("gametype");
      this.cachedReply.write("SMP");
      this.cachedReply.write("game_id");
      this.cachedReply.write("MINECRAFT");
      this.cachedReply.write("version");
      this.cachedReply.write(this.server.getVersion());
      this.cachedReply.write("plugins");
      this.cachedReply.write(this.server.getPlugins());
      this.cachedReply.write("map");
      this.cachedReply.write(this.worldName);
      this.cachedReply.write("numplayers");
      this.cachedReply.write("" + this.d());
      this.cachedReply.write("maxplayers");
      this.cachedReply.write("" + this.maxPlayers);
      this.cachedReply.write("hostport");
      this.cachedReply.write("" + this.serverPort);
      this.cachedReply.write("hostip");
      this.cachedReply.write(this.hostname);
      this.cachedReply.write((int) 0);
      this.cachedReply.write((int) 1);
      this.cachedReply.write("player_");
      this.cachedReply.write((int) 0);
      String[] astring = this.server.getPlayers();
      byte b0 = (byte) astring.length;

      for (byte b1 = (byte) (b0 - 1); b1 >= 0; --b1) {
        this.cachedReply.write(astring[b1]);
      }

      this.cachedReply.write((int) 0);
      return this.cachedReply.getBytes();
    }
  }
  @Override
  public void send(DatagramPacket packet) {
    SocketAddress socketAddress = packet.getSocketAddress();
    if (!peerAddressToChannel.containsKey(socketAddress)) {
      logger.warn("Peer {} is not bound to a channel", socketAddress);
      return;
    }

    Character channelNumber = peerAddressToChannel.get(socketAddress);

    byte[] payload = new byte[packet.getLength()];
    System.arraycopy(
        packet.getData(), packet.getOffset(), payload, packet.getOffset(), payload.length);

    ChannelData channelData = new ChannelData();
    channelData.setData(payload);
    channelData.setChannelNumber(channelNumber);

    if (logger.isTraceEnabled()) {
      logger.trace(
          "Writing {} bytes on channel {}: {}",
          packet.getLength(),
          (int) channelNumber,
          new String(payload, 0, payload.length, StandardCharsets.US_ASCII));
    }
    try {
      stunStack.sendChannelData(channelData, serverAddress, localAddress);
    } catch (StunException e) {
      throw new RuntimeException(e);
    }
  }
Example #5
0
  /**
   * Debug function
   *
   * @param log_tag
   * @param identifier part of application which called this
   * @param dp UDP datagram
   */
  public static void printPackageInfo(String log_tag, String identifier, DatagramPacket dp) {

    logByte(log_tag, "Content: " + identifier + "\n", dp.getData(), dp.getLength());
    Log.d(log_tag, Boolean.toString(dp.getAddress().isMulticastAddress()));
    Log.d(log_tag, dp.getAddress().getHostAddress());
    Log.d(log_tag, dp.getSocketAddress().toString());
  }
Example #6
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    byte[] data;
    ByteArrayInputStream inp_stream;
    DataInputStream inp = null;
    Message msg;

    while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        mcast_sock.receive(packet);
        data = packet.getData();
        inp_stream = new ExposedByteArrayInputStream(data, 0, data.length);
        inp = new DataInputStream(inp_stream);
        msg = new Message();
        msg.readFrom(inp);
        up(new Event(Event.MSG, msg));
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex);
      } finally {
        Util.close(inp);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
Example #7
0
    @Override
    protected String doInBackground(String... params) {
      WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
      if (wm != null) {
        MulticastLock mcLock = wm.createMulticastLock("SAAMS6");
        mcLock.acquire();
      }

      byte[] byteMessage = new byte[MAX_UDP_DATAGRAM_LEN];
      DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length);
      MulticastSocket socket = null;
      while (keepRunning) {
        try {
          socket = new MulticastSocket(UDP_SERVER_PORT);
          socket.receive(packet);
          String message = new String(byteMessage, 0, packet.getLength());

          if (message.equals("SAMMS6 Server")) {
            ServerIP = packet.getSocketAddress().toString();
            socket.close();
            keepRunning = false;
          }
        } catch (Throwable e) {
          e.printStackTrace();
        }
      }

      return ServerIP;
    }
Example #8
0
  // Check if the datagramsocket adaptor can send with a packet
  // that has not been initialized with an address; the legacy
  // datagram socket will send in this case
  private static void test2() throws Exception {
    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    byte b[] = "hello".getBytes("UTF-8");
    DatagramPacket pkt = new DatagramPacket(b, b.length);
    sndChannel.socket().send(pkt);

    ByteBuffer bb = ByteBuffer.allocate(256);
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    // Check that the pkt got set with the target address;
    // This is legacy behavior
    if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
  @Override
  protected void run() throws Exception {
    while (isRunning()) {

      // PACKET RECEIVED

      socket.receive(packet);
      int length = packet.getLength();
      byte[] data = ByteBuffer.allocate(length).put(packet.getData(), 0, length).array();
      SocketAddress address = packet.getSocketAddress();

      // ALLOCATE CLIENT
      SWGClient client =
          (!connections.containsKey(address))
              ? clientFactory.create(address)
              : connections.get(address);

      data = packagingService.disassemble(data, client.getCrc());

      if (data.length == 1) {
        // TODO: Queue logout packet
        // TODO:  Disconnect client
      } else if (data.length == 0) {

      } else {

        // TODO: Create SWG Message from data

      }
    }
  }
  public void run() {
    while (true) {
      try {
        // System.out.println("Waiting for client on port " +serverSocket.getLocalPort() + "...");
        byte[] receiveBuffer = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
        UDPserverSocket.receive(receivePacket);
        System.out.println(
            "Request received from "
                + receivePacket.getSocketAddress()
                + ":"
                + receivePacket.getPort());

        // Start new 'Servant' thread and make it serve the peer
        new Servant(receivePacket, UDPserverSocket).start();
        // socketFromPeer.close();

      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
 public void run() {
   while (running) {
     try {
       // create a buffer for the datagram packet
       byte[] buf = new byte[XMOSLedTilePacketPayload.MAX_PAYLOAD_SIZE];
       // receive a packet
       DatagramPacket packet = new DatagramPacket(buf, buf.length);
       socket.receive(packet);
       LOGGER.debug("Packet received {}", packet);
       // analyze the data if it is a XMOS packet
       byte[] data = packet.getData();
       // we must have at least XMOS + package ID
       if (data.length > 5) {
         byte[] magicString = new byte[MAGIC_STRING.length()];
         System.arraycopy(data, 0, magicString, 0, MAGIC_STRING.length());
         String packageMagicString = new String(magicString);
         if (MAGIC_STRING.equals(packageMagicString)) {
           LOGGER.info(
               "Retrieved a XMOS package from {}:{}",
               packet.getAddress(),
               packet.getSocketAddress());
           addPacket(packet);
         }
       }
     } catch (IOException e) {
       LOGGER.error("Unable to retrieve packet, ignoring it.", e);
     }
   }
 }
Example #12
0
  private boolean parsePacket(DatagramPacket datagrampacket) {
    byte[] abyte = datagrampacket.getData();
    int i = datagrampacket.getLength();
    SocketAddress socketaddress = datagrampacket.getSocketAddress();

    this.debug("Packet len " + i + " [" + socketaddress + "]");
    if (3 <= i && -2 == abyte[0] && -3 == abyte[1]) {
      this.debug("Packet \'" + StatusChallengeUtils.a(abyte[2]) + "\' [" + socketaddress + "]");
      switch (abyte[2]) {
        case 0:
          if (!this.hasChallenged(datagrampacket).booleanValue()) {
            this.debug("Invalid challenge [" + socketaddress + "]");
            return false;
          } else if (15 == i) {
            this.send(this.getFullReply(datagrampacket), datagrampacket);
            this.debug("Rules [" + socketaddress + "]");
          } else {
            RemoteStatusReply remotestatusreply = new RemoteStatusReply(1460);

            remotestatusreply.write((int) 0);
            remotestatusreply.write(this.getIdentityToken(datagrampacket.getSocketAddress()));
            remotestatusreply.write(this.localAddress);
            remotestatusreply.write("SMP");
            remotestatusreply.write(this.worldName);
            remotestatusreply.write(Integer.toString(this.d()));
            remotestatusreply.write(Integer.toString(this.maxPlayers));
            remotestatusreply.write((short) this.serverPort);
            remotestatusreply.write(this.hostname);
            this.send(remotestatusreply.getBytes(), datagrampacket);
            this.debug("Status [" + socketaddress + "]");
          }

        case 9:
          this.createChallenge(datagrampacket);
          this.debug("Challenge [" + socketaddress + "]");
          return true;

        default:
          return true;
      }
    } else {
      this.debug("Invalid packet [" + socketaddress + "]");
      return false;
    }
  }
Example #13
0
  /** Processes whatever's in the queue. */
  private void processIncomingPacketQueue() {
    while (_enabled) {
      QueueEntry entry;

      synchronized (_incomingQueue) {
        if (_incomingQueue.size() <= 0) {
          // nothing left, so clear flag and return
          _isProcessingIncomingQueue = false;

          return;
        }

        entry = _incomingQueue.remove();
      }

      DatagramPacket dp = entry.packet;
      String source = entry.source;

      try {
        // parse packet
        NameServicesChannelMessage message = this.parsePacket(dp);

        // handle message
        this.handleIncomingMessage(source, (InetSocketAddress) dp.getSocketAddress(), message);

      } catch (Exception exc) {
        if (!_enabled) break;

        // log nested exception summary instead of stack-trace dump
        _logger.warn(
            "{} while handling received packet from {}: {}",
            source,
            dp.getSocketAddress(),
            Exceptions.formatExceptionGraph(exc));

      } finally {
        // make sure the packet is returned
        UDPPacketRecycleQueue.instance().returnPacket(entry.packet);
      }
    } // (while)
  }
  public static void main(String[] args) throws IOException {
    if (args[0].equals("listen")) {
      final LinkedBlockingQueue<Pair<InetSocketAddress, byte[]>> queue;
      queue = new LinkedBlockingQueue<Pair<InetSocketAddress, byte[]>>();

      DatagramSocket socket = new DatagramSocket(8888);
      System.out.println(socket.getLocalAddress());

      new Thread() {
        public void run() {
          while (true) {
            Pair<InetSocketAddress, byte[]> pair;

            try {
              pair = queue.take();
            } catch (InterruptedException exc) {
              break;
            }

            System.out.println();
            System.out.println(pair.first());
            System.out.println(Text.ascii(pair.second()));
          }
        }
      }.start();

      byte[] buffer = new byte[4 * 1024];

      while (true) {
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        byte[] data = Arrays.copyOf(buffer, packet.getLength());
        InetSocketAddress addr = (InetSocketAddress) packet.getSocketAddress();

        Pair<InetSocketAddress, byte[]> pair;
        pair = new Pair<InetSocketAddress, byte[]>(addr, data);
        try {
          queue.put(pair);
        } catch (InterruptedException exc) {
          break;
        }
      }
    } else if (args[0].equals("shout")) {
      DatagramSocket socket = new DatagramSocket();
      System.out.println(socket.getLocalSocketAddress());

      byte[] data = Text.ascii("hello world");
      DatagramPacket packet = new DatagramPacket(data, 0, data.length);
      packet.setAddress(InetAddress.getByName("localhost"));
      packet.setPort(8888);
      socket.send(packet);
    }
  }
Example #15
0
 protected void cycleOperation() {
   if (!socket.isClosed()) {
     try {
       while (!buffer.isEmpty()) {
         DatagramPacket packet = (DatagramPacket) buffer.remove();
         socket.send(packet);
         logger.debug("Sent packet to " + packet.getSocketAddress());
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  /** Returns true if the client has a valid auth, otherwise false */
  private Boolean verifyClientAuth(DatagramPacket par1DatagramPacket) {
    SocketAddress var2 = par1DatagramPacket.getSocketAddress();

    if (!queryClients.containsKey(var2)) {
      return Boolean.valueOf(false);
    } else {
      byte[] var3 = par1DatagramPacket.getData();
      return ((RConThreadQueryAuth) queryClients.get(var2)).getRandomChallenge()
              != RConUtils.getBytesAsBEint(var3, 7, par1DatagramPacket.getLength())
          ? Boolean.valueOf(false)
          : Boolean.valueOf(true);
    }
  }
Example #17
0
  private Boolean hasChallenged(DatagramPacket datagrampacket) {
    SocketAddress socketaddress = datagrampacket.getSocketAddress();

    if (!this.challenges.containsKey(socketaddress)) {
      return Boolean.valueOf(false);
    } else {
      byte[] abyte = datagrampacket.getData();

      return ((RemoteStatusChallenge) this.challenges.get(socketaddress)).getToken()
              != StatusChallengeUtils.c(abyte, 7, datagrampacket.getLength())
          ? Boolean.valueOf(false)
          : Boolean.valueOf(true);
    }
  }
Example #18
0
  public void run() {
    channel.workerThread = Thread.currentThread();
    final MulticastSocket socket = channel.socket;

    while (channel.isOpen()) {
      synchronized (channel.interestOpsLock) {
        while (!channel.isReadable()) {
          try {
            // notify() is not called at all.
            // close() and setInterestOps() calls Thread.interrupt()
            channel.interestOpsLock.wait();
          } catch (InterruptedException e) {
            if (!channel.isOpen()) {
              break;
            }
          }
        }
      }

      ReceiveBufferSizePredictor predictor = channel.getConfig().getReceiveBufferSizePredictor();

      byte[] buf = new byte[predictor.nextReceiveBufferSize()];
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.receive(packet);
      } catch (InterruptedIOException e) {
        // Can happen on interruption.
        // Keep receiving unless the channel is closed.
        continue;
      } catch (Throwable t) {
        if (!channel.socket.isClosed()) {
          fireExceptionCaught(channel, t);
        }
        break;
      }

      fireMessageReceived(
          channel,
          channel.getConfig().getBufferFactory().getBuffer(buf, 0, packet.getLength()),
          packet.getSocketAddress());
    }

    // Setting the workerThread to null will prevent any channel
    // operations from interrupting this thread from now on.
    channel.workerThread = null;

    // Clean up.
    close(channel, succeededFuture(channel));
  }
  /** Parses an incoming DatagramPacket, returning true if the packet was valid */
  private boolean parseIncomingPacket(DatagramPacket par1DatagramPacket) throws IOException {
    byte[] var2 = par1DatagramPacket.getData();
    int var3 = par1DatagramPacket.getLength();
    SocketAddress var4 = par1DatagramPacket.getSocketAddress();
    logDebug("Packet len " + var3 + " [" + var4 + "]");

    if (3 <= var3 && -2 == var2[0] && -3 == var2[1]) {
      logDebug("Packet \'" + RConUtils.getByteAsHexString(var2[2]) + "\' [" + var4 + "]");

      if (var2[2] == 9) {
        sendAuthChallenge(par1DatagramPacket);
        logDebug("Challenge [" + var4 + "]");
        return true;
      } else {
        if (!verifyClientAuth(par1DatagramPacket).booleanValue()) {
          logDebug("Invalid challenge [" + var4 + "]");
          return false;
        } else {
          Response response = ResponseRegistry.getResponse(var2[2]);
          if (response == null) {
            return false;
          }
          byte[] bt =
              response.getResponceByte(
                  getRequestId(par1DatagramPacket.getSocketAddress()), par1DatagramPacket);
          logDebug(new String(bt));
          sendResponsePacket(bt, par1DatagramPacket);
          logDebug("Case " + var2[2] + " [" + var4 + "] ");
          return true;
        }
      }
    } else {
      logDebug("Invalid packet [" + var4 + "]");
      return false;
    }
  }
Example #20
0
  @Override
  public void run() {

    BotAIManagement.getLogger()
        .debug(
            "Processing packet " + "({}): {}",
            (InetSocketAddress) mRecievedDatagramPacket.getSocketAddress(),
            new String(mRecievedDatagramPacket.getData(), 0, mRecievedDatagramPacket.getLength()));

    BotAI aCorrespondingBotAI =
        BotAIManagement.getInstance()
            .getMapOfBotAIs()
            .get(mRecievedDatagramPacket.getSocketAddress());

    if (aCorrespondingBotAI != null) {

      aCorrespondingBotAI.processDatagrammPacket(mRecievedDatagramPacket);

    } else {

      Creator.putUnkownSenderDatagramInProcessingQueue(
          new UnkownBotAI(mBotAIConnect, mRecievedDatagramPacket));
    }
  }
  /** This is the body of the listening thread */
  public void run() {
    SocketAddress sender;

    checkBuffer();

    try {
      listen:
      while (isListening) {
        try {
          byteBuf.clear();

          // temporary until we work out a better way...
          // Fixed buffer size limits the maximum size of received packets
          // Seems there are always limitations and a default going back to the constant
          // DEFAULTBUFSIZE
          byte[] buffer = new byte[getBufferSize()];
          DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

          ms.receive(dp);
          byteBuf.put(buffer);
          sender = dp.getSocketAddress();

          if (!isListening) break listen;
          if ((target != null)) continue listen;

          flipDecodeDispatch(sender);
        } catch (ClosedChannelException e1) { // bye bye, we have to quit
          if (isListening) {
            //							System.err.println( e1 );
            System.err.println(
                "OSCReceiver.run : " + e1.getClass().getName() + " : " + e1.getLocalizedMessage());
          }
          return;
        } catch (IOException e1) {
          if (isListening) {
            System.err.println(
                "OSCReceiver.run : " + e1.getClass().getName() + " : " + e1.getLocalizedMessage());
            //							System.err.println( new OSCException( OSCException.RECEIVE, e1.toString() ));
          }
        }
      } // while( isListening )
    } finally {
      synchronized (threadSync) {
        thread = null;
        threadSync.notifyAll(); // stopListening() might be waiting
      }
    }
  }
Example #22
0
  @Override
  public Packet receive() throws ChannelException {
    final byte[] data = new byte[MAX_DATA_LENGTH];
    final DatagramPacket datagramPacket = new DatagramPacket(data, data.length);

    try {
      socket.receive(datagramPacket);
    } catch (IOException e) {
      close();
      throw new ChannelException("could not receive datagram packet", e);
    }

    Packet packet = new NetworkPacket();
    packet.pack(Arrays.copyOf(datagramPacket.getData(), datagramPacket.getLength()));
    packet.setRemoteAddress(datagramPacket.getSocketAddress());
    return packet;
  }
Example #23
0
  @Override
  protected int doReadMessages(MessageBuf<Object> buf) throws Exception {
    if (readSuspended) {
      try {
        Thread.sleep(SO_TIMEOUT);
      } catch (InterruptedException e) {
        // ignore;
      }
      return 0;
    }

    int packetSize = config().getReceivePacketSize();
    byte[] data = new byte[packetSize];
    tmpPacket.setData(data);
    try {
      socket.receive(tmpPacket);
      InetSocketAddress remoteAddr = (InetSocketAddress) tmpPacket.getSocketAddress();
      if (remoteAddr == null) {
        remoteAddr = remoteAddress();
      }
      buf.add(
          new DatagramPacket(
              Unpooled.wrappedBuffer(data, tmpPacket.getOffset(), tmpPacket.getLength()),
              remoteAddr));

      if (readSuspended) {
        return 0;
      } else {
        return 1;
      }
    } catch (SocketTimeoutException e) {
      // Expected
      return 0;
    } catch (SocketException e) {
      if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
        throw e;
      }
      return -1;
    }
  }
Example #24
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    DataInput inp;

    while (sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        sock.receive(packet);
        inp =
            new ByteArrayDataInputStream(packet.getData(), packet.getOffset(), packet.getLength());
        Message msg = new Message();
        msg.readFrom(inp);
        up(msg);
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error(Util.getMessage("FailedReceivingPacketFrom"), packet.getSocketAddress(), ex);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
Example #25
0
  public static void main(String[] args) throws IOException {

    final DatagramSocket ds = new DatagramSocket(9000);
    final Set<String> address = new HashSet<String>();
    boolean flag = true;
    while (flag) { // 无数据,则循环
      byte[] receiveByte = new byte[640 + 4];
      DatagramPacket dataPacket = new DatagramPacket(receiveByte, receiveByte.length);
      ds.receive(dataPacket);
      byte[] tmpBuf = null;

      String line = dataPacket.getSocketAddress().toString();
      String head = new String(Arrays.copyOf(receiveByte, 4));

      if ("play".equals(head)) { // 播放
        address.add(line);
      } else {
        tmpBuf = Arrays.copyOf(receiveByte, size);
      }
      if ("audi".equals(head) || "draw".equals(head)) { // 音频 绘图
        for (String a : address) {
          String host = a.split(":")[0].substring(1);
          int port = Integer.parseInt(a.split(":")[1]);
          try {
            if (tmpBuf != null) {
              DatagramPacket packet =
                  new DatagramPacket(tmpBuf, tmpBuf.length, InetAddress.getByName(host), port);
              ds.send(packet);
            }
          } catch (UnknownHostException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    ds.close();
  }
  /**
   * Determines whether a specific {@code DatagramPacket} is accepted by {@link #channelDataSocket}
   * (i.e. whether {@code channelDataSocket} understands {@code packet} and {@code packet} is meant
   * to be received by {@code channelDataSocket}).
   *
   * @param packet the {@code DatagramPacket} which is to be checked whether it is accepted by
   *     {@code channelDataSocket}
   * @return {@code true} if {@code channelDataSocket} accepts {@code packet} (i.e. {@code
   *     channelDataSocket} understands {@code packet} and {@code p} is meant to be received by
   *     {@code channelDataSocket}); otherwise, {@code false}
   */
  private boolean isChannelData(DatagramPacket packet) {
    // Is it from our TURN server?
    if (!serverAddress.equals(packet.getSocketAddress())) {
      return false;
    }

    int packetLength = packet.getLength();

    if (packetLength < (CHANNELDATA_CHANNELNUMBER_LENGTH + CHANNELDATA_LENGTH_LENGTH)) {
      return false;
    }

    byte[] pData = packet.getData();
    int pOffset = packet.getOffset();

    /*
     * The first two bits should be 0b01 because of the current channel number range 0x4000 - 0x7FFE. But 0b10 and 0b11
     * which are currently reserved and may be used in the future to extend the range of channel numbers.
     */
    if ((pData[pOffset] & 0xC0) == 0) {
      return false;
    }

    pOffset += CHANNELDATA_CHANNELNUMBER_LENGTH;
    packetLength -= CHANNELDATA_CHANNELNUMBER_LENGTH;

    int length = ((pData[pOffset++] << 8) | (pData[pOffset] & 0xFF));

    int padding = ((length % 4) > 0) ? 4 - (length % 4) : 0;

    /*
     * The Length field specifies the length in bytes of the Application Data field. The Length field does not include
     * the padding that is sometimes present in the data of the DatagramPacket.
     */
    return length == packetLength - padding - CHANNELDATA_LENGTH_LENGTH
        || length == packetLength - CHANNELDATA_LENGTH_LENGTH;
  }
 /**
  * Sends an auth challenge DatagramPacket to the client and adds the client to the queryClients
  * map
  */
 private void sendAuthChallenge(DatagramPacket par1DatagramPacket) throws IOException {
   RConThreadQueryAuth var2 = new RConThreadQueryAuth(this, par1DatagramPacket);
   queryClients.put(par1DatagramPacket.getSocketAddress(), var2);
   sendResponsePacket(var2.getChallengeValue(), par1DatagramPacket);
 }
Example #28
0
  public Vote lookForLeader() throws InterruptedException {
    try {
      self.jmxLeaderElectionBean = new LeaderElectionBean();
      MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
    } catch (Exception e) {
      LOG.warn("Failed to register with JMX", e);
      self.jmxLeaderElectionBean = null;
    }

    try {
      self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
      // We are going to look for a leader by casting a vote for ourself
      byte requestBytes[] = new byte[4];
      ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
      byte responseBytes[] = new byte[28];
      ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
      /* The current vote for the leader. Initially me! */
      DatagramSocket s = null;
      try {
        s = new DatagramSocket();
        s.setSoTimeout(200);
      } catch (SocketException e1) {
        LOG.error("Socket exception when creating socket for leader election", e1);
        System.exit(4);
      }
      DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length);
      DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length);
      HashMap<InetSocketAddress, Vote> votes =
          new HashMap<InetSocketAddress, Vote>(self.quorumPeers.size());
      int xid = epochGen.nextInt();
      while (self.running) {
        votes.clear();
        requestBuffer.clear();
        requestBuffer.putInt(xid);
        requestPacket.setLength(4);
        HashSet<Long> heardFrom = new HashSet<Long>();
        for (QuorumServer server : self.quorumPeers.values()) {
          LOG.info("Server address: " + server.addr);
          try {
            requestPacket.setSocketAddress(server.addr);
          } catch (IllegalArgumentException e) {
            // Sun doesn't include the address that causes this
            // exception to be thrown, so we wrap the exception
            // in order to capture this critical detail.
            throw new IllegalArgumentException(
                "Unable to set socket address on packet, msg:"
                    + e.getMessage()
                    + " with addr:"
                    + server.addr,
                e);
          }

          try {
            s.send(requestPacket);
            responsePacket.setLength(responseBytes.length);
            s.receive(responsePacket);
            if (responsePacket.getLength() != responseBytes.length) {
              LOG.error("Got a short response: " + responsePacket.getLength());
              continue;
            }
            responseBuffer.clear();
            int recvedXid = responseBuffer.getInt();
            if (recvedXid != xid) {
              LOG.error("Got bad xid: expected " + xid + " got " + recvedXid);
              continue;
            }
            long peerId = responseBuffer.getLong();
            heardFrom.add(peerId);
            // if(server.id != peerId){
            Vote vote = new Vote(responseBuffer.getLong(), responseBuffer.getLong());
            InetSocketAddress addr = (InetSocketAddress) responsePacket.getSocketAddress();
            votes.put(addr, vote);
            // }
          } catch (IOException e) {
            LOG.warn("Ignoring exception while looking for leader", e);
            // Errors are okay, since hosts may be
            // down
          }
        }
        ElectionResult result = countVotes(votes, heardFrom);
        if (result.winner.id >= 0) {
          self.setCurrentVote(result.vote);
          if (result.winningCount > (self.quorumPeers.size() / 2)) {
            self.setCurrentVote(result.winner);
            s.close();
            Vote current = self.getCurrentVote();
            self.setPeerState(
                (current.id == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
            if (self.getPeerState() == ServerState.FOLLOWING) {
              Thread.sleep(100);
            }
            return current;
          }
        }
        Thread.sleep(1000);
      }
      return null;
    } finally {
      try {
        if (self.jmxLeaderElectionBean != null) {
          MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
        }
      } catch (Exception e) {
        LOG.warn("Failed to unregister with JMX", e);
      }
      self.jmxLeaderElectionBean = null;
    }
  }
    public void run() {
      try {
        Vector<String> res = new Vector<String>();

        System.out.println("Received answer from a service ");
        boolean read = true;
        boolean jump = false;
        // char temp=(char)buf[0];
        res.add("SOURCE: " + receivePacket.getSocketAddress());

        StringBuilder sb = new StringBuilder(buf.length);
        for (byte b : buf) {
          if (jump) // salta (char)0x0A
          jump = false;
          else {
            if (b == 0) {
              read = false;
              break;
            }
            if ((char) b != (char) (0x0D)) sb.append((char) b);
            else {
              jump = true;
              res.add(sb.toString());
              sb = new StringBuilder(buf.length);
            }
          }
        }

        Vector<String> mess;
        String serviceAdd = null;
        int servicePort = -1;
        int masterPort = -1;

        String uuid = null;
        BoundReceiveSocket masterSocket = null;

        for (String line : res) {
          if (line.contains("uuid")) {
            String[] peace = line.split("uuid:");
            uuid = peace[1].substring(0, 36);
          }
          if (line.contains("LOCATION")) {
            String[] peace;
            if (line.charAt(9) == (char) 0x20) peace = line.split("LOCATION: http://");
            else peace = line.split("LOCATION:http://");

            peace = peace[1].split("/");
            peace = peace[0].split(":");
            serviceAdd = peace[0];

            servicePort = Integer.parseInt(peace[1]);
          }
          if (uuid != null && serviceAdd != null && servicePort > -1) {

            break;
          }
        }
        UPnPSOAPLocalServiceHandler temp = null;
        synchronized (UPnPmanager.lockNewLocalService) {
          temp = UPnPmanager.getLocalService(uuid);
          if (temp == null) {
            try {
              masterSocket = E2EComm.bindPreReceive(E2EComm.TCP);
              masterPort = masterSocket.getLocalPort();
              // sendService(msg);
              UPnPSOAPLocalServiceHandler handler =
                  new UPnPSOAPLocalServiceHandler(uuid, masterSocket);
              UPnPmanager.addLocalServiceHandler(handler);
              handler.start();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          if (temp != null) {
            masterSocket = temp.getMasterSocket();
            masterPort = masterSocket.getLocalPort();
          }
        }

        sendService(msg, traversedNode, serviceAdd, servicePort, masterPort, uuid, buf);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
 /**
  * Sends a byte array as a DatagramPacket response to the client who sent the given DatagramPacket
  */
 private void sendResponsePacket(byte[] par1ArrayOfByte, DatagramPacket par2DatagramPacket)
     throws IOException {
   querySocket.send(
       new DatagramPacket(
           par1ArrayOfByte, par1ArrayOfByte.length, par2DatagramPacket.getSocketAddress()));
 }