Java Code Examples for java.net.DatagramSocket#send()

The following examples show how to use java.net.DatagramSocket#send() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UDPServer.java    From code with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    try {

        DatagramSocket socket = new DatagramSocket(65001);
        byte[] buff = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buff, buff.length);
        // 接收客户端发送的内容,封装到DatagramPacket中
        socket.receive(packet);

        byte[] data = packet.getData();
        // 将字节流转为字符串(输出)
        String content = new String(data, 0, packet.getLength());
        System.out.println(content);
        // 将字符串转为字节流(回写给客户端)
        byte[] bytes = String.valueOf(content.length()).getBytes();

        DatagramPacket packetToClient = new DatagramPacket(bytes, bytes.length, packet.getAddress(), packet.getPort());

        socket.send(packetToClient);

    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 2
Source File: PortScanUDP.java    From HttpInfo with Apache License 2.0 6 votes vote down vote up
public static PortBean.PortNetBean scanAddress(InetAddress ia, int portNo, int timeoutMillis) {
    PortBean.PortNetBean portNetBean = new PortBean.PortNetBean();
    Long time = System.currentTimeMillis();
    try {
        byte[] bytes = new byte[128];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

        DatagramSocket ds = new DatagramSocket();
        ds.setSoTimeout(timeoutMillis);
        ds.connect(ia, portNo);
        ds.send(dp);
        ds.isConnected();
        ds.receive(dp);
        ds.close();
        portNetBean.setConnected(true);
    } catch (SocketTimeoutException e) {

    } catch (Exception ignore) {

    }
    portNetBean.setPort(portNo);
    portNetBean.setDelay(System.currentTimeMillis() - time);
    return portNetBean;
}
 
Example 3
Source File: Packet.java    From Kore with Apache License 2.0 6 votes vote down vote up
/**
 * Sends this packet to the EventServer
 * @param adr Address of the EventServer
 * @param port Port of the EventServer
 * @throws IOException
 */
public void send(InetAddress adr, int port) throws IOException
{
	int maxseq = getNumPackets();
	DatagramSocket s = new DatagramSocket();
	// For each Packet in Sequence...
	for(int seq=1;seq<=maxseq;seq++)
	{
		// Get Message and send them...
		byte[] pack = getUDPMessage(seq);
		DatagramPacket p = new DatagramPacket(pack, pack.length);
		p.setAddress(adr);
		p.setPort(port);
		s.send(p);
	}
}
 
Example 4
Source File: UDPTimeServer.java    From sockslib with Apache License 2.0 6 votes vote down vote up
public void shutdown() {
  try {
    DatagramSocket clientSocket = new DatagramSocket();
    String shutdownSignal = "shutdown";
    byte[] sendBuffer = shutdownSignal.getBytes();
    DatagramPacket packet =
        new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost",
            port));
    clientSocket.send(packet);
  } catch (IOException e) {
    logger.error(e.getMessage(), e);
  }
  stop = true;
  if (thread != null) {
    thread.interrupt();
  }
}
 
Example 5
Source File: UdpSource.java    From Azzet with Open Software License 3.0 5 votes vote down vote up
@Override
public InputStream getStream( String request ) throws Exception
{
	byte[] path = getAbsolute( request ).getBytes();

	DatagramPacket outgoing = new DatagramPacket( path, path.length );
	DatagramPacket incoming = new DatagramPacket( new byte[packetSize], packetSize );

	DatagramSocket s = new DatagramSocket();
	s.connect( address );
	s.send( outgoing );
	s.receive( incoming );

	return new DatagramInputStream( incoming.getData(), 0, incoming.getLength(), s );
}
 
Example 6
Source File: BroadcastDiscovery.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *  Starts a new thread to reply to broadcast discovery requests from nodes.
 *
 * @throws SocketException if cannot bind UDP socket
 * @throws UnknownHostException if cannot bind to 0.0.0.0
 */
public void start() throws SocketException, UnknownHostException {
    broadcastSocket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
    broadcastSocket.setBroadcast(true);

    discoveryThread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (;;) {
                try {
                    DatagramPacket nodePacket = new DatagramPacket(new byte[0], 0);
                    broadcastSocket.receive(nodePacket);

                    byte[] urlAsBytes = url.getBytes(BroadcastDiscoveryClient.BROADCAST_ENCODING);
                    DatagramPacket replyPacket = new DatagramPacket(urlAsBytes,
                                                                    urlAsBytes.length,
                                                                    nodePacket.getAddress(),
                                                                    nodePacket.getPort());
                    broadcastSocket.send(replyPacket);
                } catch (SocketException e) {
                    if (needsToStop) {
                        return;
                    } else {
                        logger.warn("Could not broadcast URL to node", e);
                    }
                } catch (Exception e) {
                    logger.warn("Could not broadcast URL to node", e);
                }
            }
        }
    }, "BroadcastDiscovery");
    discoveryThread.start();
}
 
Example 7
Source File: DiscoverySocketThread.java    From LocalNetwork with MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        int port = NetworkUtil.BASE_PORT;
        boolean portAvailable = false;
        do {
            if (NetworkUtil.available(port))
                portAvailable = true;
            else
                port--;
        } while (!portAvailable);

        socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
        socket.setBroadcast(true);

        while (true) {
            // Receive broadcast packet
            Log.d("USER", "Waiting for packet...");
            byte[] buffer = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(receivePacket);
            Log.d("USER", "Received packet from: " + receivePacket.getAddress().getHostAddress());

            // Send reply
            byte[] replyPacket = SerializationUtil.serialize(reply);
            socket.send(new DatagramPacket(replyPacket, replyPacket.length, receivePacket.getAddress(), receivePacket.getPort()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: UDPServer.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception { // 所有异常抛出
    String str = "hello World!!!";
    DatagramSocket ds = new DatagramSocket(3000); // 服务端在3000端口上等待服务器发送信息
    DatagramPacket dp =
        new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"), 9000); // 所有的信息使用buf保存
    System.out.println("发送信息。");
    ds.send(dp); // 发送信息出去
    ds.close();
}
 
Example 9
Source File: WiFiBox.java    From MilightAPI with MIT License 5 votes vote down vote up
/**
 * This function sends an array of bytes to the WiFi box. The bytes should
 * be a valid command, i.e. the array's length should be three.
 * 
 * @param messages
 *            is an array of message codes to send
 * @throws IllegalArgumentException
 *             if the length of the array is not 3
 * @throws IOException
 *             if the message could not be sent
 */
private void sendMessage(byte[] messages) throws IOException {
	// check arguments
	if (messages.length != 3) {
		throw new IllegalArgumentException(
				"The message to send should consist of exactly 3 bytes.");
	}

	// notify listeners
	notifyLightListeners(messages);

	// send message
	DatagramSocket socket = new DatagramSocket();
	DatagramPacket packet = new DatagramPacket(messages, messages.length,
			address, port);
	socket.send(packet);
	socket.close();

	// adjust currently active group of lights
	switch (messages[0]) {
	case COMMAND_GROUP_1_ON:
	case COMMAND_GROUP_1_OFF:
		activeGroup = 1;
		break;
	case COMMAND_GROUP_2_ON:
	case COMMAND_GROUP_2_OFF:
		activeGroup = 2;
		break;
	case COMMAND_GROUP_3_ON:
	case COMMAND_GROUP_3_OFF:
		activeGroup = 3;
		break;
	case COMMAND_GROUP_4_ON:
	case COMMAND_GROUP_4_OFF:
		activeGroup = 4;
		break;
	}
}
 
Example 10
Source File: SimpleUdpClient.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void run() throws IOException {
  InetAddress IPAddress = InetAddress.getByName(host);
  byte[] sendData = request.getBytes();
  byte[] receiveData = new byte[65535];
  // Use the provided socket if there is one, else just make a new one.
  DatagramSocket socket = this.clientSocket == null ?
      new DatagramSocket() : this.clientSocket;

  try {
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
        IPAddress, port);
    socket.send(sendPacket);
    socket.setSoTimeout(500);
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
        receiveData.length);
    socket.receive(receivePacket);

    // Check reply status
    XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
        receivePacket.getLength()));
    RpcReply reply = RpcReply.read(xdr);
    if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
      throw new IOException("Request failed: " + reply.getState());
    }
  } finally {
    // If the client socket was passed in to this UDP client, it's on the
    // caller of this UDP client to close that socket.
    if (this.clientSocket == null) {
      socket.close();
    }
  }
}
 
Example 11
Source File: LanServerBroadcastThread.java    From settlers-remake with MIT License 5 votes vote down vote up
private void broadcast(int udpPort, DatagramSocket socket, byte[] data) throws IOException {
	for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
		for (InetAddress address : Collections.list(iface.getInetAddresses())) {
			if (!address.isSiteLocalAddress())
				continue;
			// Java 1.5 doesn't support getting the subnet mask, so try the two most common.
			byte[] ip = address.getAddress();
			ip[3] = -1; // 255.255.255.0
			socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), udpPort));
			ip[2] = -1; // 255.255.0.0
			socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), udpPort));
		}
	}
}
 
Example 12
Source File: SimpleUdpClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
public void run() throws IOException {
  InetAddress IPAddress = InetAddress.getByName(host);
  byte[] sendData = request.getBytes();
  byte[] receiveData = new byte[65535];
  // Use the provided socket if there is one, else just make a new one.
  DatagramSocket socket = this.clientSocket == null ?
      new DatagramSocket() : this.clientSocket;

  try {
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
        IPAddress, port);
    socket.send(sendPacket);
    socket.setSoTimeout(500);
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
        receiveData.length);
    socket.receive(receivePacket);

    // Check reply status
    XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
        receivePacket.getLength()));
    RpcReply reply = RpcReply.read(xdr);
    if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
      throw new IOException("Request failed: " + reply.getState());
    }
  } finally {
    // If the client socket was passed in to this UDP client, it's on the
    // caller of this UDP client to close that socket.
    if (this.clientSocket == null) {
      socket.close();
    }
  }
}
 
Example 13
Source File: TestPortmap.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testRegistration() throws IOException, InterruptedException {
  XDR req = new XDR();
  RpcCall.getInstance(++xid, RpcProgramPortmap.PROGRAM,
      RpcProgramPortmap.VERSION,
      RpcProgramPortmap.PMAPPROC_SET,
      new CredentialsNone(), new VerifierNone()).write(req);

  PortmapMapping sent = new PortmapMapping(90000, 1,
      PortmapMapping.TRANSPORT_TCP, 1234);
  sent.serialize(req);

  byte[] reqBuf = req.getBytes();
  DatagramSocket s = new DatagramSocket();
  DatagramPacket p = new DatagramPacket(reqBuf, reqBuf.length,
      pm.getUdpServerLoAddress());
  try {
    s.send(p);
  } finally {
    s.close();
  }

  // Give the server a chance to process the request
  Thread.sleep(100);
  boolean found = false;
  @SuppressWarnings("unchecked")
  Map<String, PortmapMapping> map = (Map<String, PortmapMapping>) Whitebox
      .getInternalState(pm.getHandler(), "map");

  for (PortmapMapping m : map.values()) {
    if (m.getPort() == sent.getPort()
        && PortmapMapping.key(m).equals(PortmapMapping.key(sent))) {
      found = true;
      break;
    }
  }
  Assert.assertTrue("Registration failed", found);
}
 
Example 14
Source File: BroadcastDiscoveryClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void broadcastToDefaultInterface(DatagramSocket broadcastSocket) {
    try {
        DatagramPacket sendPacket = new DatagramPacket(new byte[0],
                                                       0,
                                                       InetAddress.getByName("255.255.255.255"),
                                                       port);
        broadcastSocket.send(sendPacket);
    } catch (Exception e) {
        logger.warn("Could not broadcast to default interface", e);
    }
}
 
Example 15
Source File: utils.java    From JavaLinuxNet with Apache License 2.0 5 votes vote down vote up
public static void sendTestUDP(int size) throws IOException {
    byte[] buffer = new byte[size];
    InetAddress address = InetAddress.getByName(TESTIP);
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, TESTPORT);
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
}
 
Example 16
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private void test3()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageAttributeException,
        MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 3 including response
      DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      sendSocket.connect(InetAddress.getByName(stunServer), port);
      sendSocket.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      changeRequest.setChangePort();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      sendSocket.send(send);
      LOGGER.debug("Test 3: Binding Request sent.");

      int localPort = sendSocket.getLocalPort();
      InetAddress localAddress = sendSocket.getLocalAddress();

      sendSocket.close();

      DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
      receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort());
      receiveSocket.setSoTimeout(timeout);

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        receiveSocket.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return;
      }
      if (nodeNatted) {
        di.setRestrictedCone();
        LOGGER.debug("Node is behind a restricted NAT.");
        return;
      }
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 3: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        LOGGER.debug(
            "Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        di.setPortRestrictedCone();
        LOGGER.debug("Node is behind a port restricted NAT.");
        return;
      }
    }
  } while (true);
}
 
Example 17
Source File: TP.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void sendResponse(DatagramSocket sock, SocketAddress sender, byte[] buf) throws IOException {
    DatagramPacket p=new DatagramPacket(buf, 0, buf.length, sender);
    sock.send(p);
}
 
Example 18
Source File: RRCTask.java    From Mobilyzer with Apache License 2.0 4 votes vote down vote up
/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * 
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize,
    int port) throws IOException {

  long startTime = 0;
  long endTime = 0;
  byte[] buf = new byte[size];
  byte[] rcvBuf = new byte[packetSize];
  long[] retval = {-1, -1};
  long numLost = 0;
  int i = 0;
  long dataConsumedThisTask = 0;

  DatagramSocket socket = new DatagramSocket();
  DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
  DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);
  
  // number * (packet sent + packet received)
  dataConsumedThisTask += num * (size + packetSize);

  try {
    socket.setSoTimeout(7000);
    startTime = System.currentTimeMillis();
    Logger.d("Sending packet, waiting for response ");
    for (i = 0; i < num; i++) {
      socket.send(packet);
    }
    for (i = 0; i < num; i++) {
      socket.receive(packetRcv);
      if (i == 0) {

        endTime = System.currentTimeMillis();
      }
    }
  } catch (SocketTimeoutException e) {
    Logger.d("Timed out");
    numLost += (num - i);
    socket.close();
  }
  Logger.d("Sending complete: " + endTime);

  retval[0] = endTime - startTime;
  retval[1] = numLost;

  incrementData(dataConsumedThisTask);
  return retval;
}
 
Example 19
Source File: TestListenUDP.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void run(final DatagramSocket socket, final List<String> messages, final int expectedQueueSize, final int expectedTransferred)
        throws IOException, InterruptedException {

    try {
        // schedule to start listening on a random port
        final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory();
        final ProcessContext context = runner.getProcessContext();
        proc.onScheduled(context);
        Thread.sleep(100);

        // get the real port the dispatcher is listening on
        final int destPort = proc.getDispatcherPort();
        final InetSocketAddress destination = new InetSocketAddress("localhost", destPort);

        // send the messages to the port the processors is listening on
        for (final String message : messages) {
            final byte[] buffer = message.getBytes(StandardCharsets.UTF_8);
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, destination);
            socket.send(packet);
            Thread.sleep(10);
        }

        long responseTimeout = 10000;

        // this first loop waits until the internal queue of the processor has the expected
        // number of messages ready before proceeding, we want to guarantee they are all there
        // before onTrigger gets a chance to run
        long startTimeQueueSizeCheck = System.currentTimeMillis();
        while (proc.getQueueSize() < expectedQueueSize
                && (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) {
            Thread.sleep(100);
        }

        // want to fail here if the queue size isn't what we expect
        Assert.assertEquals(expectedQueueSize, proc.getQueueSize());

        // call onTrigger until we processed all the messages, or a certain amount of time passes
        int numTransferred = 0;
        long startTime = System.currentTimeMillis();
        while (numTransferred < expectedTransferred  && (System.currentTimeMillis() - startTime < responseTimeout)) {
            proc.onTrigger(context, processSessionFactory);
            numTransferred = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS).size();
            Thread.sleep(100);
        }

        // should have transferred the expected events
        runner.assertTransferCount(ListenUDP.REL_SUCCESS, expectedTransferred);
    } finally {
        // unschedule to close connections
        proc.onUnscheduled();
        IOUtils.closeQuietly(socket);
    }
}
 
Example 20
Source File: UdpTest.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void discover() throws Exception {

    InetAddress server = InetAddress.getByName("127.0.0.1");

    Node from = Node.instanceOf("127.0.0.1:10002");
    Node peer1 = Node.instanceOf("127.0.0.1:10003");
    Node peer2 = Node.instanceOf("127.0.0.1:10004");

    Assert.assertTrue(!nodeManager.hasNodeHandler(peer1));
    Assert.assertTrue(!nodeManager.hasNodeHandler(peer2));
    Assert.assertTrue(nodeManager.getTable().getAllNodes().isEmpty());

    PingMessage pingMessage = new PingMessage(from, nodeManager.getPublicHomeNode());
    DatagramPacket pingPacket = new DatagramPacket(pingMessage.getSendData(),
        pingMessage.getSendData().length, server, port);

    FindNodeMessage findNodeMessage = new FindNodeMessage(from, Node.getNodeId());
    DatagramPacket findNodePacket = new DatagramPacket(findNodeMessage.getSendData(),
        findNodeMessage.getSendData().length, server, port);

    DatagramSocket socket = new DatagramSocket();

    // send ping msg
    socket.send(pingPacket);
    byte[] data = new byte[1024];
    DatagramPacket packet = new DatagramPacket(data, data.length);

    boolean pingFlag = false;
    boolean pongFlag = false;
    boolean findNodeFlag = false;
    boolean neighborsFlag = false;
    while (true) {
      socket.receive(packet);
      byte[] bytes = Arrays.copyOfRange(data, 0, packet.getLength());
      Message msg = Message.parse(bytes);
      Assert.assertTrue(
          Arrays.equals(msg.getFrom().getId(), nodeManager.getPublicHomeNode().getId()));
      if (!pingFlag) {
        pingFlag = true;
        Assert.assertTrue(msg instanceof PingMessage);
        Assert.assertTrue(Arrays.equals(((PingMessage) msg).getTo().getId(), from.getId()));
        PongMessage pongMessage = new PongMessage(from, msg.getTimestamp());
        DatagramPacket pongPacket = new DatagramPacket(pongMessage.getSendData(),
            pongMessage.getSendData().length, server, port);
        socket.send(pongPacket);
      } else if (!pongFlag) {
        pongFlag = true;
        Assert.assertTrue(msg instanceof PongMessage);
      } else if (!findNodeFlag) {
        findNodeFlag = true;
        Assert.assertTrue(msg instanceof FindNodeMessage);
        List<Node> peers = Lists.newArrayList(peer1, peer2);
        NeighborsMessage neighborsMessage = new NeighborsMessage(from, peers, msg.getTimestamp());
        DatagramPacket neighborsPacket = new DatagramPacket(neighborsMessage.getSendData(),
            neighborsMessage.getSendData().length, server, port);
        socket.send(neighborsPacket);
        socket.send(findNodePacket);
      } else if (!neighborsFlag) {
        Assert.assertTrue(msg instanceof NeighborsMessage);
        break;
      }
    }

    Assert.assertTrue(nodeManager.hasNodeHandler(peer1));

    Assert.assertTrue(nodeManager.hasNodeHandler(peer2));

    Assert.assertTrue(nodeManager.getTable().getAllNodes().size() == 1);

    socket.close();

  }