Ejemplo n.º 1
1
 public void run() { // Listen for packets
   tracker.startReceive(System.currentTimeMillis());
   try {
     runLoop();
   } catch (Throwable t) {
     // Impossible? It keeps on exiting. We get the below,
     // but not this...
     try {
       System.err.print(t.getClass().getName());
       System.err.println();
     } catch (Throwable tt) {
     }
     ;
     try {
       System.err.print(t.getMessage());
       System.err.println();
     } catch (Throwable tt) {
     }
     ;
     try {
       System.gc();
       System.runFinalization();
       System.gc();
       System.runFinalization();
     } catch (Throwable tt) {
     }
     try {
       Runtime r = Runtime.getRuntime();
       System.err.print(r.freeMemory());
       System.err.println();
       System.err.print(r.totalMemory());
       System.err.println();
     } catch (Throwable tt) {
     }
     ;
     try {
       t.printStackTrace();
     } catch (Throwable tt) {
     }
     ;
   } finally {
     System.err.println("run() exiting for UdpSocketHandler on port " + _sock.getLocalPort());
     Logger.error(this, "run() exiting for UdpSocketHandler on port " + _sock.getLocalPort());
     synchronized (this) {
       _isDone = true;
       notifyAll();
     }
   }
 }
  @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.º 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
  /**
   * 将事件发送到指定的目的地址
   *
   * @param e
   * @param addr
   * @param port
   * @return
   */
  public void sendEvent(Event e, InetAddress addr, int port) throws Exception {
    Events events = new Events();
    events.addEvent(e);
    Log log = new Log();
    log.setEvents(events);

    StringWriter writer = new StringWriter();
    try {
      Marshaller.marshal(log, writer);
    } catch (MarshalException e1) {
      log().warn("marshall log error : " + e1, e1);
    } catch (ValidationException e1) {
      log().warn("marshall log error : " + e1, e1);
    }

    String dataXml = writer.toString();

    if (StringUtils.trimToNull(dataXml) == null) {
      log().error("event cannot marshall " + e);
      throw new Exception("event cannot marshall");
    }

    byte[] data = dataXml.getBytes();

    m_pkt = new DatagramPacket(data, data.length);
    //		m_pkt.setAddress(InetAddress.getByName("127.0.0.1"));
    //		m_pkt.setPort(5817);
    System.out.println("add is : " + addr);
    System.out.println("port is : " + port);
    System.out.println("m_dgSocket is : " + m_dgSocket.getLocalPort());
    m_pkt.setAddress(addr);
    m_pkt.setPort(port);
    m_dgSocket.send(m_pkt);
  }
Ejemplo n.º 5
0
 /** Receive loop for private messaqes. Can be stopped with {@link #setRunning(boolean)} */
 private void receivePrivateMessages() {
   while (isRunning()) {
     try {
       final byte[] buf = new byte[BUFFER_SIZE];
       final DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Waiting for private message, listening on port " + privateSocket.getLocalPort());
       }
       privateSocket.receive(receivePacket); // wait for a packet
       final String data = toString(receivePacket);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Got a private message: " + data);
       }
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Received "
                 + data
                 + " from "
                 + receivePacket.getAddress()
                 + ":"
                 + receivePacket.getPort()
                 + ".");
       }
       processPrivateMessage(data);
     } catch (IOException e) {
       LOG.error(BUNDLE_MARKER, e.toString(), e);
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Stopped listening to private messages.");
   }
 }
Ejemplo n.º 6
0
  private ByteArrayOutputStream receiveFile() {
    ByteArrayOutputStream byteOuput = new ByteArrayOutputStream();
    int block = 1;
    do {
      try {
        System.out.println("TFTP Packet Count:" + block);
        block++;
        bufferByteArray = new byte[516];
        inDatagramPacket =
            new DatagramPacket(
                bufferByteArray, bufferByteArray.length, address, datagramSocket.getLocalPort());
        datagramSocket.receive(inDatagramPacket);
        byte opCode = bufferByteArray[1];

        if (opCode == OP_ERROR) {
          reportError();
        } else if (opCode == OP_DATA) {
          byte[] blockNumber = {bufferByteArray[2], bufferByteArray[3]};
          DataOutputStream output = new DataOutputStream(byteOuput);
          output.write(inDatagramPacket.getData(), 4, inDatagramPacket.getLength() - 4);

          sendAck(blockNumber);
        }

      } catch (IOException ex) {
        Logger.getLogger(TFTPClient.class.getName()).log(Level.SEVERE, null, ex);
      }

    } while (!isLastPacket(inDatagramPacket));
    return byteOuput;
  }
  /**
   * Activate this <tt>UDPTerminal</tt>.
   *
   * @throws Exception if there is a network failure.
   */
  public synchronized void activate() throws Exception {
    if (!isActive()) {
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::activate()::laddr=:" + m_LocalAddress + ":lport=" + m_LocalPort);

      if (m_Socket == null) {
        if (m_LocalAddress != null && m_LocalPort != -1) {
          m_Socket = new DatagramSocket(m_LocalPort, m_LocalAddress);
        } else {
          m_Socket = new DatagramSocket();
          m_LocalPort = m_Socket.getLocalPort();
          m_LocalAddress = m_Socket.getLocalAddress();
        }
      }
      if (Modbus.debug) CCLog.info("UDPMasterTerminal::haveSocket():" + m_Socket.toString());
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::laddr=:" + m_LocalAddress.toString() + ":lport=" + m_LocalPort);
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::raddr=:" + m_RemoteAddress.toString() + ":rport=" + m_RemotePort);

      m_Socket.setReceiveBufferSize(1024);
      m_Socket.setSendBufferSize(1024);

      m_ModbusTransport = new ModbusUDPTransport(this);
      m_Active = true;
    }
    if (Modbus.debug) CCLog.info("UDPMasterTerminal::activated");
  }
Ejemplo n.º 8
0
  /**
   * Activate this <tt>UDPTerminal</tt>.
   *
   * @throws Exception if there is a network failure.
   */
  public synchronized void activate() throws Exception {
    if (!isActive()) {
      if (Modbus.debug) System.out.println("UDPSlaveTerminal.activate()");
      if (m_Socket == null) {
        if (m_LocalAddress != null && m_LocalPort != -1) {
          m_Socket = new DatagramSocket(m_LocalPort, m_LocalAddress);
        } else {
          m_Socket = new DatagramSocket();
          m_LocalPort = m_Socket.getLocalPort();
          m_LocalAddress = m_Socket.getLocalAddress();
        }
      }
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::haveSocket():" + m_Socket.toString());
      if (Modbus.debug)
        System.out.println(
            "UDPSlaveTerminal::addr=:" + m_LocalAddress.toString() + ":port=" + m_LocalPort);

      m_Socket.setReceiveBufferSize(1024);
      m_Socket.setSendBufferSize(1024);
      m_PacketReceiver = new PacketReceiver();
      m_Receiver = new Thread(m_PacketReceiver);
      m_Receiver.start();
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::receiver started()");
      m_PacketSender = new PacketSender();
      m_Sender = new Thread(m_PacketSender);
      m_Sender.start();
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::sender started()");
      m_ModbusTransport = new ModbusUDPTransport(this);
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::transport created");
      m_Active = true;
    }
    if (Modbus.debug) System.out.println("UDPSlaveTerminal::activated");
  }
Ejemplo n.º 9
0
  public static void doEcho(int port) throws IOException {
    byte[] buf = new byte[BUF_SIZE];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    DatagramSocket sock = new DatagramSocket(port);

    System.out.println(
        "Starting UDP echo on"
            + sock.getLocalAddress().getHostAddress()
            + ":"
            + sock.getLocalPort());
    while (true) {
      try {
        sock.receive(packet);
        sock.send(packet);
        System.out.print(
            "UDP From: "
                + packet.getAddress().getHostAddress()
                + ":"
                + packet.getPort()
                + "\n"
                + new String(packet.getData(), 0, packet.getLength())
                + "\n");
        System.out.flush();

        packet.setLength(buf.length);
        // packet = new DatagramPacket(buf,buf.length);
      } catch (IOException io_ex) {
      }
    }
  }
Ejemplo n.º 10
0
  public TcpUdpBridgeServer(
      String remoteTcpHost, String remoteUdpHost, int remoteTcpPort, int remoteUdpPort) {
    this.remoteTcpHost = remoteTcpHost;
    this.remoteUdpHost = remoteUdpHost;
    this.remoteTcpPort = remoteTcpPort;
    this.remoteUdpPort = remoteUdpPort;

    try {
      serverTcpSocket = new ServerSocket(remoteTcpPort);
      localUdpSocket = new DatagramSocket(0);
      localUdpPort = localUdpSocket.getLocalPort();
      LOGGER.fine("UDP: " + localUdpSocket.getLocalPort());
    } catch (IOException e) {
      e.printStackTrace();
    }
    startBridge();
  }
Ejemplo n.º 11
0
 public RequestReceiver(int port) throws IOException {
   UDPserverSocket = new DatagramSocket(port);
   System.out.println(
       "UDP Request Receiver Running on "
           + UDPserverSocket.getInetAddress()
           + ":"
           + UDPserverSocket.getLocalPort());
   UDPserverSocket.setSoTimeout(0);
 }
Ejemplo n.º 12
0
 static String printSocket(DatagramSocket socket) {
   return "[Socket: localPort="
       + socket.getLocalPort()
       + ", remoteAddr="
       + socket.getInetAddress()
       + ", localAddr="
       + socket.getLocalAddress()
       + "]";
 }
 /** Sends a single broadcast discovery request. */
 private void sendProbe() {
   DatagramPacket packet = makeRequestPacket(DESIRED_SERVICE, mSocket.getLocalPort());
   try {
     mSocket.send(packet);
   } catch (IOException e) {
     Log.e(LOG_TAG, "Exception sending broadcast probe", e);
     return;
   }
 }
Ejemplo n.º 14
0
 /**
  * ローカル接続データを
  *
  * @param connectionData
  */
 private void addLocalData(ConnectionData connectionData) {
   if (localDataSend) {
     try {
       connectionData.setLocalAddress(InetAddress.getLocalHost().getHostAddress());
       connectionData.setLocalPort(socket.getLocalPort());
       System.out.println(connectionData.encode());
     } catch (Exception e) {
     }
   }
 }
Ejemplo n.º 15
0
 public InetSocketAddress getLocalAddress() throws IOException {
   synchronized (generalSync) {
     if (ms != null) {
       final DatagramSocket ds = ms;
       return getLocalAddress(ds.getLocalAddress(), ds.getLocalPort());
     } else {
       return getLocalAddress(localAddress.getAddress(), localAddress.getPort());
     }
   }
 }
Ejemplo n.º 16
0
  void closeSocket() {
    if (sock != null) {
      // by sending a dummy packet, the thread will terminate (if it was flagged as stopped before)
      sendDummyPacket(sock.getLocalAddress(), sock.getLocalPort());

      sock.close();
      sock = null;
      if (Trace.trace) {
        Trace.info("UDP.closeSocket()", "socket closed");
      }
    }
  }
Ejemplo n.º 17
0
  /**
   * Send a block of encoded bytes to a peer. This is called by send, and by
   * IncomingPacketFilter.processOutgoing(..).
   *
   * @param blockToSend The data block to send.
   * @param destination The peer to send it to.
   */
  public void sendPacket(byte[] blockToSend, Peer destination, boolean allowLocalAddresses)
      throws LocalAddressException {
    assert (blockToSend != null);
    if (!_active) {
      Logger.error(this, "Trying to send packet but no longer active");
      // It is essential that for recording accurate AddressTracker data that we don't send any more
      // packets after shutdown.
      return;
    }
    // there should be no DNS needed here, but go ahead if we can, but complain doing it
    if (destination.getAddress(false, allowLocalAddresses) == null) {
      Logger.error(
          this,
          "Tried sending to destination without pre-looked up IP address(needs a real Peer.getHostname()): null:"
              + destination.getPort(),
          new Exception("error"));
      if (destination.getAddress(true, allowLocalAddresses) == null) {
        Logger.error(
            this,
            "Tried sending to bad destination address: null:" + destination.getPort(),
            new Exception("error"));
        return;
      }
    }
    if (_dropProbability > 0) {
      if (dropRandom.nextInt() % _dropProbability == 0) {
        Logger.normal(this, "DROPPED: " + _sock.getLocalPort() + " -> " + destination.getPort());
        return;
      }
    }
    InetAddress address = destination.getAddress(false, allowLocalAddresses);
    assert (address != null);
    int port = destination.getPort();
    DatagramPacket packet = new DatagramPacket(blockToSend, blockToSend.length);
    packet.setAddress(address);
    packet.setPort(port);

    try {
      _sock.send(packet);
      tracker.sentPacketTo(destination);
      collector.addInfo(address + ":" + port, 0, blockToSend.length + UDP_HEADERS_LENGTH);
      if (logMINOR)
        Logger.minor(
            this, "Sent packet length " + blockToSend.length + " to " + address + ':' + port);
    } catch (IOException e) {
      if (packet.getAddress() instanceof Inet6Address) {
        Logger.normal(
            this, "Error while sending packet to IPv6 address: " + destination + ": " + e, e);
      } else {
        Logger.error(this, "Error while sending packet to " + destination + ": " + e, e);
      }
    }
  }
Ejemplo n.º 18
0
 public DirectoryServer(int port) throws Exception {
   super("Directory Server", false);
   boolean connected = false;
   try {
     udp_socket = new DatagramSocket(port);
     System.out.println("The DirectoryServer UDP socket was bound to port: " + port);
   } catch (SocketException e) {
     udp_socket = new DatagramSocket();
     System.out.println(
         "The DirectoryServer UDP socket was bound to port: " + udp_socket.getLocalPort());
   }
   udp_socket.setSoTimeout(Server.TIMEOUT_Server);
   dsu = new DirectoryServerUDP(this);
   if (Application.db_dir == null) {
     db_dir = getDirDB(Application.CURRENT_DATABASE_DIR() + Application.DIRECTORY_FILE);
     Application.db_dir = db_dir;
   } else db_dir = Application.db_dir;
   do {
     try {
       if (port <= 0) port = Server.getRandomPort();
       ss = new ServerSocket(port);
       connected = true;
     } catch (Exception e) {
       e.printStackTrace();
       connected = false;
       port = Server.getRandomPort();
     }
   } while (!connected);
   System.out.println("Got port: " + ss.getLocalPort());
   /*
   System.out.println("Got net: "+ss.getInetAddress());
   System.out.println("Got sock: "+ss.getLocalSocketAddress());
   System.out.println("Got obj: "+ss);
    */
   Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
   for (NetworkInterface netint : Collections.list(nets)) {
     out.printf("Display name: %s\n", netint.getDisplayName());
     out.printf(
         "Name: %s (loopback: %s; p2p:%s; up: %s, v: %s, m:%s)\n",
         netint.getName(),
         "" + netint.isLoopback(),
         "" + netint.isPointToPoint(),
         "" + netint.isUp(),
         "" + netint.isVirtual(),
         "" + netint.supportsMulticast());
     Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     for (InetAddress inetAddress : Collections.list(inetAddresses)) {
       out.printf("inetAddress: %s\n", inetAddress);
     }
   }
   initAcceptedInets();
 }
Ejemplo n.º 19
0
  /**
   * Empfangen einer Nachricht ueber UDP
   *
   * @return Referenz auf Nachricht, die empfangen wurde
   * @param timeout Wartezeit in ms
   * @throws IOException
   */
  public Object receive(int timeout) throws IOException, SocketTimeoutException {
    // Maximale Wartezeit fuer Receive am Socket einstellen
    try {
      log.info("RECEIVE MIT TIMEOUT: " + timeout);
      socket.setSoTimeout(timeout);
      // System.out.println("RECEIVE: Maximale Wartezeit: " +
      // timeout +" ms");
    } catch (SocketException e) {
      log.error("RECEIVE: " + "Fehler beim Einstellen der maximalen Wartezeit");
      throw e;
    }

    byte[] bytes = new byte[65527];
    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    // System.out.println("VOR: Empfangene Datenlaenge:  " + packet.getLength());
    try {
      // Blockiert nur, bis Timeout abgelaufen ist
      socket.receive(packet);
      log.debug("RECEIVE: Empfangene Datenlaenge:  " + packet.getLength());
      System.out.println("RECEIVE: Empfangene Datenlaenge:  " + packet.getLength());

    } catch (IOException e2) {
      log.error("RECEIVE: " + "Fehler beim Empfangen einer PDU ueber UDP", e2);
      throw e2;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData());
    ObjectInputStream ois = new ObjectInputStream(bais);

    Object pdu;
    try {

      // System.out.println("RECEIVE: " +
      // "Verfuegbare Bytes Inputstream des UDP-Sockets:" +
      // ois.available());

      pdu = ois.readObject();

      remoteAddress = packet.getAddress();
      remotePort = packet.getPort();

      log.debug("RECEIVE: " + packet.getPort() + "->" + socket.getLocalPort());

    } catch (ClassNotFoundException e) {
      log.error("RECEIVE: " + "ClassNotFoundException:", e);
      return null;
    }

    log.info("RECEIVE MIT TIMEOUT ENDE: " + timeout);
    return pdu;
  }
Ejemplo n.º 20
0
  public ClientTransaction preProcessInvite(SipRequest sipRequest) throws SipUriSyntaxException {

    // 8.1.2
    SipHeaders requestHeaders = sipRequest.getSipHeaders();
    SipURI destinationUri = RequestManager.getDestinationUri(sipRequest, logger);

    // TODO if header route is present, addrspec = toproute.nameaddress.addrspec

    String transport = RFC3261.TRANSPORT_UDP;
    Hashtable<String, String> params = destinationUri.getUriParameters();
    if (params != null) {
      String reqUriTransport = params.get(RFC3261.PARAM_TRANSPORT);
      if (reqUriTransport != null) {
        transport = reqUriTransport;
      }
    }
    int port = destinationUri.getPort();
    if (port == SipURI.DEFAULT_PORT) {
      port = RFC3261.TRANSPORT_DEFAULT_PORT;
    }
    SipURI sipUri = userAgent.getConfig().getOutboundProxy();
    if (sipUri == null) {
      sipUri = destinationUri;
    }
    InetAddress inetAddress;
    try {
      inetAddress = InetAddress.getByName(sipUri.getHost());
    } catch (UnknownHostException e) {
      throw new SipUriSyntaxException("unknown host: " + sipUri.getHost(), e);
    }
    ClientTransaction clientTransaction =
        transactionManager.createClientTransaction(
            sipRequest, inetAddress, port, transport, null, this);
    DatagramSocket datagramSocket;
    synchronized (this) {
      datagramSocket = getDatagramSocket();
    }
    try {
      SessionDescription sessionDescription =
          sdpManager.createSessionDescription(null, datagramSocket.getLocalPort());
      sipRequest.setBody(sessionDescription.toString().getBytes());
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    }
    requestHeaders.add(
        new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE),
        new SipHeaderFieldValue(RFC3261.CONTENT_TYPE_SDP));
    return clientTransaction;
  }
 @Test
 public void sendEventsTest() throws IOException, InterruptedException, ServerError {
   final DatagramSocket serverSocket = new DatagramSocket();
   try {
     final RiemannClient client =
         new RiemannClient(new SimpleUdpTransport(serverSocket.getLocalPort()));
     try {
       client.connect();
       sendTestMessages(serverSocket, client);
     } finally {
       client.disconnect();
     }
   } finally {
     serverSocket.close();
   }
 }
Ejemplo n.º 22
0
  private void printState(PrintStream out) {

    out.println("UdpSimpleSession state dumping:");
    if (sock != null) out.println("Local UDP port: " + sock.getLocalPort());
    Iterator iter = multicastReaders.keySet().iterator();
    while (iter.hasNext())
      out.println("Local Multicast address: " + ((InetSocketAddress) iter.next()));

    int nChannels = channels.size();
    out.println("Currently connected channels: " + nChannels);

    iter = channels.values().iterator();
    while (iter.hasNext()) {
      Channel c = (Channel) iter.next();
      out.println("Channel name: " + c.getChannelID() + " QoS: " + c.getQoS().getQoSID());
    }
  }
Ejemplo n.º 23
0
  public int start(int port) throws SocketException {
    if (socket != null) {
      // Server is already running
      throw new RuntimeException("Server is already running.");
    }
    if (port <= 0) {
      socket = new DatagramSocket();
    } else {
      socket = new DatagramSocket(port);
    }

    int localPort = socket.getLocalPort();
    LOGGER.info("Server is started at " + localPort);
    startReceiving();

    return localPort;
  }
 /**
  * The method queries a Stun server for a binding for the port and address that <tt>sock</tt> is
  * bound on.
  *
  * @param sock the socket whose port and address we'dlike to resolve (the stun message gets sent
  *     trhough that socket)
  * @return StunAddress the address returned by the stun server or null if an error occurred or no
  *     address was returned
  * @throws IOException if an error occurs while stun4j is using sockets.
  * @throws BindException if the port is already in use.
  */
 private StunAddress queryStunServer(DatagramSocket sock) throws IOException, BindException {
   StunAddress mappedAddress = null;
   if (detector != null && useStun) {
     mappedAddress = detector.getMappingFor(sock);
     if (logger.isTraceEnabled()) {
       logger.trace(
           "For socket with address "
               + sock.getLocalAddress().getHostAddress()
               + " and port "
               + sock.getLocalPort()
               + " the stun server returned the "
               + "following mapping ["
               + mappedAddress
               + "]");
     }
   }
   return mappedAddress;
 }
  public NetworkManager(String ipAddress, int port) {
    // Start the Network Sender thread
    // This thread will read from the mWriteToPcQueue and send packets to the PC application
    // The mWriteToPcQueue will get packets from the FT_Device write call
    try {
      mSocket = new DatagramSocket(port);
      Log.v("D2xx::", "Local Port " + mSocket.getLocalPort());
      NetworkSender myNetworkSender =
          new NetworkSender(mWriteToPcQueue, ipAddress, mSocket, port); // Runnable
      Thread networkSenderThread = new Thread(myNetworkSender);
      networkSenderThread.start();

      NetworkReceiver myNetworkReceiver = new NetworkReceiver(mReadFromPcQueue, mSocket);
      Thread networkReceiverThread = new Thread(myNetworkReceiver);
      networkReceiverThread.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
  public void run() {

    System.out.println("               -----------------UDP Demo Server-----------------" + "\n\n");

    while (true) {
      try {
        // Create a new socket connection bound to the defined port
        DatagramSocket sock = new DatagramSocket(BROADCAST_PORT);

        System.out.println("Waiting for data on local port: " + sock.getLocalPort());

        // Create a packet to contain incoming data
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        // Wait for incoming data (receive() is a blocking method)
        sock.receive(packet);

        // Retrieve data from packet and display
        String data = new String(packet.getData());
        int endIndex = data.indexOf(0);
        data = data.substring(0, endIndex);
        int remotePort = packet.getPort();
        System.out.println("Received data from remote port " + remotePort + ":\n" + data);

        // Determine origin of packet and display information
        InetAddress remoteAddress = packet.getAddress();
        System.out.println("Sent from address: " + remoteAddress.getHostAddress());

        // Send back an acknowledgment
        String ack = "RECEIVED " + new Date().toString();
        sock.send(new DatagramPacket(ack.getBytes(), ack.length(), remoteAddress, remotePort));

        sock.close();
      } catch (IOException ioe) {
        System.out.println("Error: IOException - " + ioe.toString());
      }
    }
  }
  @Before
  public void setUp() throws Exception {
    DatagramSocket serverSocket = startFakeTurnServer();

    instance = new TurnClientImpl();
    instance.scheduledExecutorService = scheduledExecutorService;
    instance.lobbyServerAccessor = lobbyServerAccessor;
    instance.turnHost = serverSocket.getLocalAddress().getHostAddress();
    instance.turnPort = serverSocket.getLocalPort();

    eventsReceivedByTurnServer = new LinkedBlockingQueue<>();

    Mockito.doAnswer(
            invocation -> {
              invocation.getArgumentAt(0, Runnable.class).run();
              return null;
            })
        .when(scheduledExecutorService)
        .execute(any());

    instance.postConstruct();
  }
Ejemplo n.º 28
0
  String dumpSocketInfo() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("local_addr=").append(local_addr);
    sb.append(", mcast_addr=").append(mcast_addr);
    sb.append(", bind_addr=").append(bind_addr);
    sb.append(", ttl=").append(ip_ttl);

    if (sock != null) {
      sb.append("\nsocket: bound to ");
      sb.append(sock.getLocalAddress().getHostAddress()).append(":").append(sock.getLocalPort());
      sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
      sb.append(", send buffer size=").append(sock.getSendBufferSize());
    }

    if (mcast_sock != null) {
      sb.append("\nmulticast socket: bound to ");
      sb.append(mcast_sock.getInterface().getHostAddress())
          .append(":")
          .append(mcast_sock.getLocalPort());
      sb.append(", send buffer size=").append(mcast_sock.getSendBufferSize());
      sb.append(", receive buffer size=").append(mcast_sock.getReceiveBufferSize());
    }
    return sb.toString();
  }
  /**
   * Log the packet.
   *
   * @param packet packet to log
   */
  @Override
  protected void doLogPacket(RawPacket packet, InetSocketAddress target) {
    if (socket == null || packet == null || target == null) return;

    // Do not log the packet if it has been processed (and already
    // logged) by the ice4j stack.
    if (socket instanceof MultiplexingDatagramSocket) return;

    PacketLoggingService pktLogging = getPacketLoggingService();

    if (pktLogging != null) {
      pktLogging.logPacket(
          PacketLoggingService.ProtocolName.RTP,
          socket.getLocalAddress().getAddress(),
          socket.getLocalPort(),
          target.getAddress().getAddress(),
          target.getPort(),
          PacketLoggingService.TransportName.UDP,
          true,
          packet.getBuffer(),
          packet.getOffset(),
          packet.getLength());
    }
  }
Ejemplo n.º 30
-1
 public UDPEcho(String host, int port) throws IOException, UnknownHostException {
   this.hostIP = InetAddress.getByName(host);
   this.port = port;
   sock = new DatagramSocket();
   System.out.println("UDP: " + sock.getLocalAddress() + ":" + sock.getLocalPort());
   // sock.connect(hostIP,port);
 }