@Test
  public void sendEventsOverReconnectionTest()
      throws IOException, InterruptedException, ServerError {
    DatagramSocket serverSocket = new DatagramSocket();
    final int port = serverSocket.getLocalPort();
    try {
      final RiemannClient client =
          new RiemannClient(new SimpleUdpTransport(serverSocket.getLocalPort()));
      try {
        client.connect();
        assertTrue(client.isConnected());
        sendTestMessages(serverSocket, client);

        // Close listening socket
        serverSocket.close();

        // Expect send to drop messages silently
        final Proto.Event e = Util.createEvent();
        client.sendEvents(e);

        // Reopen listening socket
        serverSocket = new DatagramSocket(new InetSocketAddress(port));

        // Expect sent messages to be received again
        sendTestMessages(serverSocket, client);

      } finally {
        client.disconnect();
        assertFalse(client.isConnected());
      }
    } finally {
      serverSocket.close();
    }
  }
Ejemplo n.º 2
0
  public void run() {

    try {
      while (running) {
        byte[] sendClientData = new byte[512];
        byte[] sendServerData = new byte[512];
        byte[] receiveClientData = new byte[512];
        byte[] receiveServerData = new byte[512];

        DatagramPacket receiveClientPacket = receivePacket(receiveClientData, receiveSocket);
        receiveClientPacket.getLength();
        // find port used by client
        int clientPort = receiveClientPacket.getPort();

        DatagramSocket hostSocket = new DatagramSocket();

        sendServerData = receiveClientPacket.getData();
        sendPacket(sendServerData, serverIPAddress, ServerPort, hostSocket);

        DatagramPacket receiveServerPacket = receivePacket(receiveServerData, hostSocket);
        if (receiveServerPacket.getData()[0] == 1) {
          running = false;
        }
        sendClientData = receiveServerPacket.getData();
        sendPacket(sendClientData, clientIPAddress, clientPort, hostSocket);

        hostSocket.close();
      }
      receiveSocket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  /*
   * Connect a UDP socket, disconnect it, then send and recv on it.
   * It will fail on Linux if we don't silently bind(2) again at the
   * end of DatagramSocket.disconnect().
   */
  private static void testConnectedUDP(InetAddress addr) throws Exception {
    try {
      DatagramSocket s = new DatagramSocket(0, addr);
      DatagramSocket ss = new DatagramSocket(0, addr);
      System.out.print("\tconnect...");
      s.connect(ss.getLocalAddress(), ss.getLocalPort());
      System.out.print("disconnect...");
      s.disconnect();

      byte[] data = {0, 1, 2};
      DatagramPacket p =
          new DatagramPacket(data, data.length, s.getLocalAddress(), s.getLocalPort());
      s.setSoTimeout(10000);
      System.out.print("send...");
      s.send(p);
      System.out.print("recv...");
      s.receive(p);
      System.out.println("OK");

      ss.close();
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
Ejemplo n.º 4
0
 public void stop() {
   player.stopThread();
   l1.stopThread();
   // l2.stopThread();
   synchronized (sock) {
     sock.close();
   }
   csock.close();
 }
  @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();
  }
Ejemplo n.º 6
0
 public static void main(String args[]) {
   try {
     DatagramSocket d1 = new DatagramSocket(2071);
     DatagramSocket d2 = new DatagramSocket(2081);
     UDPSender s = new UDPSender(d1);
     UDPReceiver r = new UDPReceiver(d2);
     s.t.join();
     r.t.join();
     d1.close();
     d2.close();
   } catch (Exception e) {
   }
 }
Ejemplo n.º 7
0
  public void run() {
    while (true) {
      try {
        DatagramSocket ClientSoc = new DatagramSocket(ClinetPortNumber);
        String Command = "GET";

        byte Sendbuff[] = new byte[1024];
        Sendbuff = Command.getBytes();

        InetAddress ServerHost = InetAddress.getLocalHost();
        ClientSoc.send(new DatagramPacket(Sendbuff, Sendbuff.length, ServerHost, 5217));

        byte Receivebuff[] = new byte[1024];
        DatagramPacket dp = new DatagramPacket(Receivebuff, Receivebuff.length);
        ClientSoc.receive(dp);

        NewsMsg = new String(dp.getData(), 0, dp.getLength());
        System.out.println(NewsMsg);
        lblNewsHeadline.setText(NewsMsg);

        Thread.sleep(5000);
        ClientSoc.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
Ejemplo n.º 8
0
  public void run() {

    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];

        // receive request
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet); // containing IP ecc.

        // figure out response
        String dString = null;
        if (in == null) dString = new Date().toString();
        else dString = getNextQuote();
        buf = dString.getBytes();

        // send the response to the client at "address" and "port"
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
Ejemplo n.º 9
0
 @Override
 public void endUDPBroadCast() {
   // TODO Auto-generated method stub
   if (_socket != null) {
     _socket.close();
   }
 }
Ejemplo n.º 10
0
  public void run() {
    DatagramPacket dataPacket = null;

    try {
      udpSocket = new DatagramSocket(DEFAULT_PORT);

      dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
      byte[] data = dataString.getBytes();
      dataPacket.setData(data);
      dataPacket.setLength(data.length);
      dataPacket.setPort(DEFAULT_PORT);

      InetAddress broadcastAddr;
      String ipAddress = iA.getIpAddress();
      broadcastAddr = InetAddress.getByName(ipAddress);
      dataPacket.setAddress(broadcastAddr);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // while( start ){
    try {
      udpSocket.send(dataPacket);
      sleep(10);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // }

    udpSocket.close();
  }
Ejemplo n.º 11
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
   */
  public boolean available(int port) {
    if (port < fromPort || port > toPort) {
      throw new IllegalArgumentException("Port outside port range: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException ignored) {
      /* checkstyle drives me nuts */
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException ignored) {
          /* checkstyle drives me nuts */
        }
      }
    }

    return false;
  }
Ejemplo n.º 12
0
 public void DisConnectSocket() {
   if (recvSocket != null) {
     recvSocket.close();
     recvSocket = null;
   }
   if (rPacket != null) rPacket = null;
 }
Ejemplo n.º 13
0
  /**
   * Send string over UDP to the specified address via the specified port.
   *
   * @param message string to be sent over UDP
   * @param address address to send the message to
   * @param port port number to use
   * @return true if message was successfully sent
   */
  public static boolean sendUDPString(String message, InetAddress address, int port) {
    DatagramPacket packet = null;
    boolean succeeded = true;
    packet = new DatagramPacket(message.getBytes(), message.length(), address, port);

    DatagramSocket socket = null;
    try {
      socket = new DatagramSocket();
    } catch (SocketException e1) {
      System.out.println("Error creating UDP socket");
      succeeded = false;
    }

    if (socket != null) {
      try {
        socket.send(packet);
      } catch (IOException e) {
        System.out.println("Error sending UDP packet");
        succeeded = false;
      }
      socket.close();
    }

    return succeeded;
  }
Ejemplo n.º 14
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   */
  private boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          /* should not be thrown */
        }
      }
    }

    return false;
  }
Ejemplo n.º 15
0
    @Override
    public void run() {

      DatagramSocket datagramSocket = null;

      while (isContinueListen) {
        try {
          if (datagramSocket == null) {
            datagramSocket = new DatagramSocket(null);
            datagramSocket.setReuseAddress(true);
            datagramSocket.bind(new InetSocketAddress(listenPort));
            datagramSocket.setReceiveBufferSize(512 * 1024);
          }
          byte[] buffer = new byte[1024 * 1024];
          DatagramPacket udpPacket = new DatagramPacket(buffer, buffer.length);

          datagramSocket.receive(udpPacket);

          LPP.put(udpPacket);
          Logg.e(TAG, "收到2000包");
        } catch (Exception e) {
          e.printStackTrace();
          Logg.e(TAG, "收到2000包 error");
          continue;
        }
      }
      if (datagramSocket != null) {
        datagramSocket.close();
        datagramSocket = null;
      }
    }
Ejemplo n.º 16
0
 // kill it with fire!
 public boolean close() {
   if (!socket.isClosed() || socket.isConnected()) {
     socket.close();
     return true;
   }
   return false;
 }
Ejemplo n.º 17
0
  private static boolean available(int port) {
    if (port <= 0) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      LogKit.logNothing(e);
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          // should not be thrown, just detect port available.
          LogKit.logNothing(e);
        }
      }
    }
    return false;
  }
Ejemplo n.º 18
0
  // start up the server
  public void start() {
    DatagramSocket socket = null;
    try {
      // create a datagram socket, bind to port port. See
      // http://docs.oracle.com/javase/tutorial/networking/datagrams/ for
      // details.

      socket = new DatagramSocket(port);

      // receive packets in an infinite loop
      while (true) {
        // create an empty UDP packet
        byte[] buf = new byte[Server.MAX_PACKET_SIZE];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // call receive (this will poulate the packet with the received
        // data, and the other endpoint's info)
        socket.receive(packet);
        // start up a worker thread to process the packet (and pass it
        // the socket, too, in case the
        // worker thread wants to respond)
        WorkerThread t = new WorkerThread(packet, socket);
        t.start();
      }
    } catch (IOException e) {
      // we jump out here if there's an error, or if the worker thread (or
      // someone else) closed the socket
      e.printStackTrace();
    } finally {
      if (socket != null && !socket.isClosed()) socket.close();
    }
  }
  /**
   * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN
   * query).
   *
   * @param dst the destination that we'd like to use this address with.
   * @param port the port whose mapping we are interested in.
   * @return a public address corresponding to the specified port or null if all attempts to
   *     retrieve such an address have failed.
   * @throws IOException if an error occurs while stun4j is using sockets.
   * @throws BindException if the port is already in use.
   */
  public InetSocketAddress getPublicAddressFor(InetAddress dst, int port)
      throws IOException, BindException {
    if (!useStun || (dst instanceof Inet6Address)) {
      logger.debug(
          "Stun is disabled for destination "
              + dst
              + ", skipping mapped address recovery (useStun="
              + useStun
              + ", IPv6@="
              + (dst instanceof Inet6Address)
              + ").");
      // we'll still try to bind though so that we could notify the caller
      // if the port has been taken already.
      DatagramSocket bindTestSocket = new DatagramSocket(port);
      bindTestSocket.close();

      // if we're here then the port was free.
      return new InetSocketAddress(getLocalHost(dst), port);
    }
    StunAddress mappedAddress = queryStunServer(port);
    InetSocketAddress result = null;
    if (mappedAddress != null) result = mappedAddress.getSocketAddress();
    else {
      // Apparently STUN failed. Let's try to temporarily disble it
      // and use algorithms in getLocalHost(). ... We should probably
      // eveng think about completely disabling stun, and not only
      // temporarily.
      // Bug report - John J. Barton - IBM
      InetAddress localHost = getLocalHost(dst);
      result = new InetSocketAddress(localHost, port);
    }
    if (logger.isDebugEnabled())
      logger.debug("Returning mapping for port:" + port + " as follows: " + result);
    return result;
  }
Ejemplo n.º 20
0
  public static void main(String[] args) throws IOException {
    /* 接受发过来的数据 */

    // 创建upd socket服务对象
    DatagramSocket ds = new DatagramSocket(10039);

    // 创建数据包,用于存储接收到的数据
    byte[] bbuf = new byte[1024];
    DatagramPacket dp = new DatagramPacket(bbuf, bbuf.length);

    // 用socket对象的receive方法将接收到的数据存储到数据包中
    ds.receive(dp);

    // 获取ip
    String ip = dp.getAddress().getHostAddress();
    int port = dp.getPort();

    // 获取数据内容
    byte[] data = dp.getData();
    String text = new String(data, 0, dp.getLength());

    System.out.println(ip + ":" + port + ":" + text);

    ds.close();
  }
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: java RFS862_UdpClient <destination host> <destination port>");
      System.exit(1);
    }
    // get the dest host + port from console
    String dest_host = args[0];
    int dest_port = Integer.parseInt(args[1]);

    // input stream from the console
    BufferedReader inFromUserConsole = new BufferedReader(new InputStreamReader(System.in));
    // new udp socket
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName(dest_host);
    // sizes of sent and received data
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    // the message from the client
    System.out.println("Please input a message:");
    String sentence = inFromUserConsole.readLine();

    sendData = sentence.getBytes();
    // build the datagram package
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, dest_port);
    // send it to the server
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    // get data from the server
    clientSocket.receive(receivePacket);
    // cast the received message as string
    String modifiedSentence = new String(receivePacket.getData());
    System.out.println(modifiedSentence);
    // close the client socket
    clientSocket.close();
  }
Ejemplo n.º 22
0
 /**
  * Closes the socket and stops the listener thread.
  *
  * @throws IOException
  */
 public void close() throws IOException {
   boolean interrupted = false;
   WorkerTask l = listener;
   if (l != null) {
     l.terminate();
     l.interrupt();
     if (socketTimeout > 0) {
       try {
         l.join();
       } catch (InterruptedException ex) {
         interrupted = true;
         logger.warn(ex);
       }
     }
     listener = null;
   }
   DatagramSocket closingSocket = socket;
   if ((closingSocket != null) && (!closingSocket.isClosed())) {
     closingSocket.close();
   }
   socket = null;
   if (interrupted) {
     Thread.currentThread().interrupt();
   }
 }
Ejemplo n.º 23
0
    public void run() {

      while (!isThreadRunning) {

        byte[] ack_byte = new byte[2];

        DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length);
        try {
          socketAck.setSoTimeout(5);
        } catch (SocketException e) {
          e.printStackTrace();
        }
        try {
          socketAck.receive(packet_ack);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] ackData = packet_ack.getData();
        int packet_ack_num = getAckPaket(ackData);
        num_acked = Math.max(num_acked, packet_ack_num);
        Thread.yield();
      }

      socketAck.close();
    }
Ejemplo n.º 24
0
 @Override
 protected void doStop() throws Exception {
   super.doStop();
   if (_socket != null) _socket.close();
   _socket = null;
   _acceptor = null;
 }
Ejemplo n.º 25
0
    @Override
    public void run() {
      Log.d(TAG, "Starting keep alive...");
      DatagramSocket socket = null;
      try {
        socket = new DatagramSocket(PORT);
        try {
          InetAddress host = InetAddress.getByName(mAddress);
          while (mTransmit) {
            byte[] buffer = {0x66};
            DatagramPacket out = new DatagramPacket(buffer, buffer.length, host, PORT);
            socket.send(out);
            sleep(mInterval);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

      } catch (SocketException e) {
        e.printStackTrace();
      } finally {
        if (socket != null) {
          socket.close();
        }
      }
    }
Ejemplo n.º 26
0
  public void destory() {
    procMsgThd.stop0();
    procMsgThd.interrupt();
    mainThread.interrupt();
    if (group != null) {
      try {
        if (recvSocket instanceof MulticastSocket) {
          ((MulticastSocket) recvSocket).leaveGroup(group);
        }
      } catch (IOException ioe) {
      }
    }

    sendSocket.close();
    recvSocket.close();
  }
Ejemplo n.º 27
0
 @Override
 public void run() {
   /* Legacy UDP location manager daemon.
    */
   DatagramPacket packet;
   while (!Thread.currentThread().isInterrupted()) {
     try {
       packet = new DatagramPacket(new byte[1024], 1024);
       socket.receive(packet);
     } catch (SocketException e) {
       if (!Thread.currentThread().isInterrupted()) {
         LOGGER.warn("Exception in Server receive loop (exiting)", e);
       }
       break;
     } catch (Exception ie) {
       LOGGER.warn("Exception in Server receive loop (exiting)", ie);
       break;
     }
     try {
       process(packet);
       socket.send(packet);
     } catch (Exception se) {
       LOGGER.warn("Exception in send ", se);
     }
   }
   socket.close();
 }
Ejemplo n.º 28
0
  public static List<Usr> getList() throws IOException {
    byte[] host_ip = InetAddress.getLocalHost().getAddress();
    DatagramSocket serverSocket = new DatagramSocket(UDP_PORT);
    byte[] buf = BROADCAST_MSG.getBytes();
    InetAddress address = InetAddress.getByName(ALL_IP);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, UDP_PORT);
    serverSocket.send(packet);
    serverSocket.setSoTimeout(SOCKET_TIMEOUT); // set the timeout in millisecounds.

    ArrayList<Usr> out = new ArrayList<Usr>();
    while (true) {
      try {
        byte[] rcv = new byte[32];
        packet = new DatagramPacket(rcv, rcv.length);
        serverSocket.receive(packet);
        byte[] ip = packet.getAddress().getAddress();
        if (Arrays.equals(ip, host_ip)) continue;
        Usr usr = new Usr(packet.getData());
        out.add(usr);
      } catch (SocketTimeoutException e) {
        break;
      }
    }

    serverSocket.close();
    return out;
  }
    protected void destroy() {
      search_destroyed = true;

      if (twc != null) {

        twc.destroy();

        twc = null;
      }

      if (timer_event != null) {

        timer_event.cancel();

        timer_event = null;
      }

      if (control_socket != null) {

        try {
          control_socket.close();

        } catch (Throwable e) {
        }

        control_socket = null;
      }
    }
Ejemplo n.º 30
0
  /**
   * checks if a specific port is available.
   *
   * @param port the port to check for availability
   */
  public static boolean isPortAvailable(int port) {
    if (port < 0 || port > 65535) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      return false;
    } finally {
      if (ds != null) {
        ds.close();
      }
      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          /* should not be thrown */
        }
      }
    }
  }