@SuppressWarnings("unchecked")
  @Test
  public void testUnicastReceiverWithReply() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    socket.send(packet);
    final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>();
    final CountDownLatch receiverReadyLatch = new CountDownLatch(1);
    final CountDownLatch replyReceivedLatch = new CountDownLatch(1);
    // main thread sends the reply using the headers, this thread will receive it
    Executors.newSingleThreadExecutor()
        .execute(
            new Runnable() {
              @Override
              public void run() {
                DatagramPacket answer = new DatagramPacket(new byte[2000], 2000);
                try {
                  receiverReadyLatch.countDown();
                  socket.receive(answer);
                  theAnswer.set(answer);
                  replyReceivedLatch.countDown();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            });
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    String replyString = "reply:" + System.currentTimeMillis();
    byte[] replyBytes = replyString.getBytes();
    DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length);
    reply.setSocketAddress(
        new InetSocketAddress(
            (String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS),
            (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT)));
    assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS));
    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.send(reply);
    assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS));
    DatagramPacket answerPacket = theAnswer.get();
    assertNotNull(answerPacket);
    assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength()));
    datagramSocket.close();
    socket.close();
    adapter.stop();
  }
  @SuppressWarnings("unchecked")
  @Test
  @Ignore
  public void testMulticastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    MulticastReceivingChannelAdapter adapter =
        new MulticastReceivingChannelAdapter("225.6.7.8", port);
    adapter.setOutputChannel(channel);
    String nic = SocketTestUtils.chooseANic(true);
    if (nic == null) { // no multicast support
      LogFactory.getLog(this.getClass()).error("No Multicast support");
      return;
    }
    adapter.setLocalAddress(nic);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("225.6.7.8", port));
    DatagramSocket datagramSocket = new DatagramSocket(0, Inet4Address.getByName(nic));
    datagramSocket.send(packet);
    datagramSocket.close();

    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    adapter.stop();
  }
  @Test
  public void testUnicastReceiverException() throws Exception {
    SubscribableChannel channel = new DirectChannel();
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    //		SocketUtils.setLocalNicIfPossible(adapter);
    adapter.setOutputChannel(channel);
    ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService());
    channel.subscribe(handler);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    DatagramSocket datagramSocket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    datagramSocket.send(packet);
    datagramSocket.close();
    Message<?> receivedMessage = errorChannel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals("Failed", ((Exception) receivedMessage.getPayload()).getCause().getMessage());
    adapter.stop();
  }
  @Test
  public void testSend() throws Exception {
    WaitForAsyncUtils.async(
        () -> {
          handleAllocationRequest();
          handleCreatePermissionRequest();
          handleChannelBindRequest();

          return null;
        });

    instance.connect().get(5, TimeUnit.SECONDS);

    InetSocketAddress remotePeerAddress = new InetSocketAddress("93.184.216.34", 1234);

    CreatePermissionMessage createPermissionMessage = new CreatePermissionMessage();
    createPermissionMessage.setAddress(remotePeerAddress);

    verify(lobbyServerAccessor)
        .addOnMessageListener(
            eq(CreatePermissionMessage.class), createPermissionListenerCaptor.capture());
    createPermissionListenerCaptor.getValue().accept(createPermissionMessage);

    byte[] bytes = new byte[1024];
    DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
    datagramPacket.setSocketAddress(remotePeerAddress);

    instance.send(datagramPacket);
  }
Ejemplo n.º 5
0
  static void write(
      OioDatagramChannel channel,
      ChannelFuture future,
      Object message,
      SocketAddress remoteAddress) {
    try {
      ChannelBuffer buf = (ChannelBuffer) message;
      int length = buf.readableBytes();
      ByteBuffer nioBuf = buf.toByteBuffer();
      DatagramPacket packet;
      if (nioBuf.hasArray()) {
        // Avoid copy if the buffer is backed by an array.
        packet = new DatagramPacket(nioBuf.array(), nioBuf.arrayOffset(), length);
      } else {
        // Otherwise it will be expensive.
        byte[] arrayBuf = new byte[length];
        buf.getBytes(0, arrayBuf);
        packet = new DatagramPacket(arrayBuf, length);
      }

      if (remoteAddress != null) {
        packet.setSocketAddress(remoteAddress);
      }
      channel.socket.send(packet);
      fireWriteComplete(channel, length);
      future.setSuccess();
    } catch (Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    }
  }
Ejemplo n.º 6
0
  protected void sendGuardSignal() throws IOException {
    final DatagramSocket guard;
    final DatagramPacket guardPacket;

    guard = new DatagramSocket();
    guardPacket = new DatagramPacket(new byte[0], 0);
    guardPacket.setSocketAddress(getLocalAddress());
    guard.send(guardPacket);
    guard.close();
  }
  private void onChannelData(ChannelDataMessageEvent event) {
    ChannelData channelData = event.getChannelDataMessage();

    if (logger.isTraceEnabled()) {
      logger.trace(
          "Received {} bytes on channel {}: {}",
          (int) channelData.getDataLength(),
          (int) channelData.getChannelNumber(),
          new String(
              channelData.getData(), 0, channelData.getDataLength(), StandardCharsets.US_ASCII));
    }

    DatagramPacket datagramPacket =
        new DatagramPacket(channelData.getData(), channelData.getDataLength());
    datagramPacket.setSocketAddress(event.getRemoteAddress());
    onPacketReceived(datagramPacket);
  }
Ejemplo n.º 8
0
  @Override
  protected void doWriteMessages(MessageBuf<Object> buf) throws Exception {
    DatagramPacket p = (DatagramPacket) buf.poll();
    ByteBuf data = p.data();
    int length = data.readableBytes();
    InetSocketAddress remote = p.remoteAddress();
    if (remote != null) {
      tmpPacket.setSocketAddress(remote);
    }
    if (data.hasArray()) {
      tmpPacket.setData(data.array(), data.arrayOffset() + data.readerIndex(), length);
    } else {
      byte[] tmp = new byte[length];
      data.getBytes(data.readerIndex(), tmp);
      tmpPacket.setData(tmp);
    }

    socket.send(tmpPacket);
  }
  private void onIndication(StunMessageEvent event) {
    Message message = event.getMessage();
    byte[] data = ((DataAttribute) message.getAttribute(Attribute.DATA)).getData();
    TransportAddress sender =
        ((XorPeerAddressAttribute) message.getAttribute(XOR_PEER_ADDRESS))
            .getAddress(message.getTransactionID());

    if (logger.isTraceEnabled()) {
      logger.trace(
          "Received {} bytes indication from '{}': {}",
          data.length,
          sender,
          new String(data, 0, data.length, StandardCharsets.US_ASCII));
    }

    DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
    datagramPacket.setSocketAddress(sender);
    onPacketReceived(datagramPacket);
  }
Ejemplo n.º 10
0
 // Broadcasts a packet containing server address to the LAN every second
 public void run() {
   try {
     DatagramSocket socket = new DatagramSocket();
     InetSocketAddress address = new InetSocketAddress("255.255.255.255", DISCOVERY_PORT);
     byte[] message = new byte[0];
     socket.setBroadcast(true);
     DatagramPacket packet = new DatagramPacket(message, message.length);
     packet.setSocketAddress(address);
     while (true) {
       socket.send(packet);
       Thread.sleep(1000);
     }
   } catch (IOException e) {
     // Port is in use, we don't know our own address or we could not send the broadcast for some
     // reason. Either way, discovery won't work.
     logger.log(Level.SEVERE, null, e);
   } catch (InterruptedException e) {
     logger.log(Level.INFO, "Discovery service shutting down");
   }
 }
Ejemplo n.º 11
0
  /** Sends the message to a recipient */
  private void sendMessage(
      DatagramSocket socket,
      String label,
      InetSocketAddress to,
      NameServicesChannelMessage message) {
    if (isSameSocketAddress(socket, to))
      _logger.info("{} sending message. to=self, message={}", label, message);
    else _logger.info("{} sending message. to={}, message={}", label, to, message);

    if (socket == null) {
      _logger.info("{} is not available yet; ignoring send request.", label);
      return;
    }

    // convert into bytes
    String json = Serialisation.serialise(message);
    byte[] bytes = json.getBytes(UTF8Charset.instance());

    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    packet.setSocketAddress(to);

    try {
      socket.send(packet);

      if (to.getAddress().isMulticastAddress()) {
        s_multicastOutData.addAndGet(bytes.length);
        s_multicastOutOps.incrementAndGet();
      } else {
        s_unicastOutData.addAndGet(bytes.length);
        s_unicastOutOps.incrementAndGet();
      }

    } catch (IOException exc) {
      if (!_enabled) return;

      if (socket.isClosed())
        _logger.info(s_sendSocketLabel + " send() ignored as socket is being recycled.");
      else _logger.warn(s_sendSocketLabel + " send() failed. ", exc);
    }
  } // (method)
  @SuppressWarnings("unchecked")
  @Test
  public void testUnicastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    //		SocketUtils.setLocalNicIfPossible(adapter);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    DatagramSocket datagramSocket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    datagramSocket.send(packet);
    datagramSocket.close();
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    adapter.stop();
  }
Ejemplo n.º 13
0
 @Override
 public void run() {
   // Open for voting
   logger.log(Level.INFO, "Beginning voting");
   voting.beginVoting();
   VotingReceiver votingService = new VotingReceiver();
   if (votingThread != null && !votingThread.isInterrupted()) {
     votingThread.interrupt();
   }
   votingThread = new Thread(votingService);
   votingThread.start();
   try {
     /*If client/server are on the same machine, broadcast may arrive at client
      * before server opens receive socket. This is not relevant on separate machines
      * but it avoids an extra voting cycle on single machine tests.
      */
     Thread.sleep(200);
     // Broadcast start of voting period
     try {
       DatagramSocket socket = new DatagramSocket();
       InetSocketAddress address = new InetSocketAddress("255.255.255.255", VOTING_PORT);
       byte[] message = new byte[0];
       socket.setBroadcast(true);
       DatagramPacket packet = new DatagramPacket(message, message.length);
       packet.setSocketAddress(address);
       socket.send(packet);
     } catch (IOException e) {
       logger.log(Level.SEVERE, null, e);
     }
     Thread.sleep(10000); // Run voting for 10 seconds
   } catch (InterruptedException ex) {
     logger.log(Level.INFO, "Voting shutting down");
   }
   votingThread.interrupt();
   voting.endVoting(MCServer.this);
 }
Ejemplo n.º 14
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;
    }
  }
  private void requestLogicServerRoom(ByteBuffer buffer) {
    int length = Integer.MIN_VALUE;
    int type = Integer.MIN_VALUE;

    int roomType = Integer.MIN_VALUE;
    int roomId = Integer.MIN_VALUE;
    String roomTitle = null;
    int peopleCount = Integer.MIN_VALUE;
    String ownerGuid = null;
    List<String> playerList = new ArrayList<String>();
    Map<String, String> heroList = new HashMap<String, String>();
    Map<String, Integer> groupList = new HashMap<String, Integer>();
    Map<String, Integer> positionList = new HashMap<String, Integer>();
    String playerGuid = null;
    int playerGroup = Integer.MIN_VALUE;
    int playerPosition = Integer.MIN_VALUE;
    String heroCardId = null;
    byte[] dst;
    while (buffer.hasRemaining()) {
      length = buffer.getInt();
      type = buffer.get();
      if (type == EnumProtocol.TYPE_INT) {
        if (roomType == Integer.MIN_VALUE) {
          roomType = buffer.getInt();
        } else if (roomId == Integer.MIN_VALUE) {
          roomId = buffer.getInt();
        } else if (peopleCount == Integer.MIN_VALUE) {
          peopleCount = buffer.getInt();
        } else if (playerGroup == Integer.MIN_VALUE) {
          playerGroup = buffer.getInt();
        } else if (playerPosition == Integer.MIN_VALUE) {
          playerPosition = buffer.getInt();
        }
      } else if (type == EnumProtocol.TYPE_STRING) {
        if (roomTitle == null) {
          dst = new byte[length];
          buffer.get(dst);
          try {
            roomTitle = new String(dst, "UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        } else if (ownerGuid == null) {
          dst = new byte[length];
          buffer.get(dst);
          try {
            ownerGuid = new String(dst, "UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        } else if (heroList.size() < peopleCount) {
          if (playerGuid == null) {
            dst = new byte[length];
            buffer.get(dst);
            try {
              playerGuid = new String(dst, "UTF-8");
            } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
            }
          } else if (heroCardId == null) {
            dst = new byte[length];
            buffer.get(dst);
            try {
              heroCardId = new String(dst, "UTF-8");
            } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
            }
          }
        }

        if (playerGuid != null
            && playerGroup != Integer.MIN_VALUE
            && playerPosition != Integer.MIN_VALUE
            && heroCardId != null) {
          heroList.put(playerGuid, heroCardId);
          groupList.put(playerGuid, playerGroup);
          positionList.put(playerGuid, playerPosition);

          playerGuid = null;
          playerGroup = Integer.MIN_VALUE;
          playerPosition = Integer.MIN_VALUE;
          heroCardId = null;
        }
      }
    }

    if (roomType == 0) {
      BattleRoom room = BattleHall.getInstance().addRoom(roomId);
      if (room != null) {
        room.setTitle(roomTitle);
        room.setPeopleCount(peopleCount);
        room.initialize();
        Iterator<Entry<String, String>> it = heroList.entrySet().iterator();
        Entry<String, String> en;
        String guid;
        while (it.hasNext()) {
          en = it.next();
          guid = en.getKey();
          room.addHeroCardId(guid, en.getValue());
          room.addPlayerGuid(guid, groupList.get(guid));
          room.addPlayerPosition(guid, positionList.get(guid));
        }

        log.info("[RequestRoom] 房间创建成功,等待客户端连接, room id = " + roomId);
        // TODO 通知GameServer创建房间成功
        DatagramPacket p = DatagramPacketPool.getInstance().getObject();
        p.setSocketAddress(LogicServer.gameServerAdd);

        ByteBuffer bf = BufferPool.getInstance().getBuffer();

        bf.putShort(EnumProtocol.BASE_REQUEST_LOGIC_SERVER_ROOM_CONFIRM);

        bf.putInt(4);
        bf.put((byte) EnumProtocol.TYPE_INT);
        bf.putInt(roomType);

        bf.putInt(4);
        bf.put((byte) EnumProtocol.TYPE_INT);
        bf.putInt(roomId);

        bf.flip();

        byte[] dest = new byte[bf.remaining()];
        bf.get(dest, 0, dest.length);

        p.setData(dest);

        GameServerConnector.getInstance().send(p);
      } else {
        log.error("[RequestRoom] 创建房间失败, room id = " + roomId);
        // TODO 通知GameServer创建房间失败
      }
    }
  }
 protected void send(DatagramPacket packet) throws Exception {
   DatagramSocket socket = this.getSocket();
   packet.setSocketAddress(this.getDestinationAddress());
   socket.send(packet);
 }