Java 类java.net.DatagramSocket 实例源码

项目:OCast-Java    文件:SSDPDiscoveryTest.java   
@Test
public void scanSingleResult() throws Exception {
    final DatagramSocket socketMessage = mock(DatagramSocket.class);
    doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(any(DatagramPacket.class));

    FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
    SSDPDiscovery ssdp = new SSDPDiscovery("urn:cast-ocast-org:service:cast:1", 3000) {
        @Override
        protected DatagramSocket createSocket() {
            return socketMessage;
        }
    };
    ssdp.addListener(callback);
    ssdp.start();
    callback.await(3, TimeUnit.SECONDS);
    verify(callback, times(1)).onLocationSent();
    verify(callback, times(1)).onLocationReceived(any(SSDPMessage.class));
    SSDPMessage result = callback.getResult();
    assertThat(result.getUuid(), is(equalTo("c4323fee-db4b-4227-9039-fa4b71589e26")));
}
项目:jdk8u-jdk    文件:SnmpRequestHandler.java   
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
项目:OCast-Java    文件:SSDPDiscoveryTest.java   
@Override
public DatagramSocket answer(InvocationOnMock invocation) throws Throwable {
    //if needed, the Socket can be retrieved with:
    //DatagramSocket socket = (DatagramSocket) invocation.getMock();
    int timeout = 5000;
    Object[] args = invocation.getArguments();
    if (mCount < mResponseToSend) {
        Thread.sleep(timeout/2);
        ((DatagramPacket) args[0]).setData(mAnswers[mCount].getBytes());
        mCount++;
        return null;
    } else {
        Thread.sleep(timeout);
        throw new InterruptedIOException();
    }
}
项目:scorekeeperfrontend    文件:Network.java   
/**
 * For multihomed machines (i.e. anything with Docker Machine), use the 
 * routing table default route to find what should be the primary network
 * facing interface.
 * @return an InetAddress for the primary address
 */
public static InetAddress getPrimaryAddress()
{
    InetAddress ret;
    try {
        DatagramSocket s = new DatagramSocket();
        s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0);
        ret = s.getLocalAddress();
        s.close();
        return ret;
    } catch (SocketException | UnknownHostException se) {
        log.info("get by route failed: " + se);
    } 

    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException ex) {
        log.info("getLocalHost failed: " + ex);
    }

    return InetAddress.getLoopbackAddress();
}
项目:OCast-Java    文件:SSDPDiscoveryTest.java   
@Test
public void testScanWithWrongST() throws Exception {
    final DatagramSocket socketMessage = mock(DatagramSocket.class);
    doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(Mockito.any(DatagramPacket.class));

    FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
    SSDPDiscovery ssdp = new SSDPDiscovery("urn:dummy:service:vucast:1", 3000) {
        @Override
        protected DatagramSocket createSocket() {
            return socketMessage;
        }
    };
    ssdp.addListener(callback);
    ssdp.start();
    callback.await(3, TimeUnit.SECONDS);
    verify(callback, times(1)).onLocationSent();
    verify(callback, times(0)).onLocationReceived(any(SSDPMessage.class));
}
项目:ipack    文件:UDPTransport.java   
public UDPTransport(DatagramSocket socket, int mtu)
    throws IOException
{

    if (!socket.isBound() || !socket.isConnected())
    {
        throw new IllegalArgumentException("'socket' must be bound and connected");
    }

    this.socket = socket;

    // NOTE: As of JDK 1.6, can use NetworkInterface.getMTU

    this.receiveLimit = mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD;
    this.sendLimit = mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD;
}
项目:Transmission    文件:BroadcastDiscover.java   
private void receiveBroadcast(DatagramSocket datagramSocket) throws IOException {
        byte[] data = new byte[2048];
        while (receive) {
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
            datagramSocket.receive(datagramPacket);
            DataResult data1 = UnPacket.getInstance().getData(datagramPacket.getData());
            if (data1 != null && data1.isResult() && data1.getT().getDataType()==Packet.DATA_TYPE_ONLINE) {
//                data1.getType()
//                TLog.e(data1.toString());
                if (listener != null) {
                    listener.receiver(data1);
                }
            }

//        String s =  new String(datagramPacket.getData());
////        TLog.e("address : " + datagramPacket.getAddress() + ", port : " + datagramPacket.getPort() + ", content : " + s);
//            if (listener!=null){
//                listener.receiver(s);
//            }
        }
    }
项目:Sem-Update    文件:VentanaPrincipal.java   
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
    try {
        // Se intenta conectar, retorna IOException en caso que no pueda
        DatagramSocket clienteSocket = new DatagramSocket();
        byte[] bufferOut = new byte[1000];

        String mensajeAMandar = "Mata server" + id;
        bufferOut = mensajeAMandar.getBytes();
        IPServer = InetAddress.getByName(servidor);

        DatagramPacket sendPacket = new DatagramPacket(bufferOut, bufferOut.length, IPServer, numeroPuerto);
        clienteSocket.send(sendPacket);

        jLabel1.setForeground(Color.red);
        clienteSocket.close();
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    } catch (IOException ex) {
        System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
        Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:boohee_v5.6    文件:Network.java   
public static String getIp() {
    IOException e;
    try {
        DatagramSocket socket = new DatagramSocket();
        try {
            socket.connect(InetAddress.getByName("114.114.114.114"), 53);
            InetAddress local = socket.getLocalAddress();
            socket.close();
            return local.getHostAddress();
        } catch (IOException e2) {
            e = e2;
            DatagramSocket datagramSocket = socket;
            e.printStackTrace();
            return "";
        }
    } catch (IOException e3) {
        e = e3;
        e.printStackTrace();
        return "";
    }
}
项目:broadlink-java-api    文件:BLDevice.java   
/**
 * Constructs a <code>BLDevice</code>, with a device type (constants),
 * hostname and MAC address
 * 
 * @param deviceType
 *            Device type constants (<code>BLDevice.DEV_*</code>)
 * @param devDesc
 *            Friendly device description
 * @param host
 *            Hostname of target Broadlink device
 * @param mac
 *            MAC address of target Broadlink device
 * @throws IOException
 *             Problems on constructing a datagram socket
 */
protected BLDevice(short deviceType, String deviceDesc, String host, Mac mac) throws IOException {
    key = INITIAL_KEY;
    iv = INITIAL_IV;
    id = new byte[] { 0, 0, 0, 0 };

    pktCount = new Random().nextInt(0xffff);
    // pktCount = 0;

    this.deviceType = deviceType;
    this.deviceDesc = deviceDesc;

    this.host = host;
    this.mac = mac;

    sock = new DatagramSocket(0);
    sock.setReuseAddress(true);
    sock.setBroadcast(true);
}
项目:fuck_zookeeper    文件:LENonTerminateTest.java   
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);

        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
项目:java-coap    文件:DatagramSocketTransportTest.java   
@Test
public void sendingCoapWithTrafficClass() throws Exception {
    final DatagramSocket socket = spy(new QoSDatagramSocket(new InetSocketAddress(0)));
    DatagramSocketTransport trans = spy(createDatagramSocketTransport());
    when(trans.createSocket()).thenReturn(socket);

    CoapClient client = CoapClientBuilder.newBuilder(5683).transport(trans).timeout(10000).build();

    client.resource("/test").context(TrafficClassTransportContext.create(TrafficClassTransportContext.HIGH, TransportContext.NULL)).get();
    verify(socket).setTrafficClass(TrafficClassTransportContext.HIGH);
    verify(socket).setTrafficClass(0);

    reset(socket);
    client.resource("/test").get();
    verify(socket, never()).setTrafficClass(anyInt());

    client.close();
}
项目:https-github.com-apache-zookeeper    文件:AuthFastLeaderElection.java   
private void starter(QuorumPeer self) {
    this.self = self;
    port = self.getVotingView().get(self.getId()).electionAddr.getPort();
    proposedLeader = -1;
    proposedZxid = -1;

    try {
        mySocket = new DatagramSocket(port);
        // mySocket.setSoTimeout(20000);
    } catch (SocketException e1) {
        e1.printStackTrace();
        throw new RuntimeException();
    }
    sendqueue = new LinkedBlockingQueue<ToSend>(2 * self.getVotingView().size());
    recvqueue = new LinkedBlockingQueue<Notification>(2 * self.getVotingView()
            .size());
    new Messenger(self.getVotingView().size() * 2, mySocket);
}
项目:BiglyBT    文件:DHTTrackerPluginAlt.java   
private
GetPeersTask(
    DatagramSocket                              _server,
    List<DHTTransportAlternativeContact>        _contacts,
    byte[]                                      _torrent_hash,
    boolean                                     _no_seeds,
    LookupListener                              _listener )
{
    server          = _server;
    torrent_hash    = _torrent_hash;
    no_seeds        = _no_seeds;
    listener        = _listener;

    initial_contacts = _contacts;

    tryQuery();
}
项目:hadoop    文件:PrivilegedNfsGatewayStarter.java   
@Override
public void init(DaemonContext context) throws Exception {
  System.err.println("Initializing privileged NFS client socket...");
  NfsConfiguration conf = new NfsConfiguration();
  int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
      NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
  if (clientPort < 1 || clientPort > 1023) {
    throw new RuntimeException("Must start privileged NFS server with '" +
        NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
        "privileged port.");
  }
  registrationSocket = new DatagramSocket(
      new InetSocketAddress("localhost", clientPort));
  registrationSocket.setReuseAddress(true);
  args = context.getArguments();
}
项目:ZooKeeper    文件:LENonTerminateTest.java   
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);

        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
项目:DecompiledMinecraft    文件:RConThreadQuery.java   
/**
 * Initializes the query system by binding it to a port
 */
private boolean initQuerySystem()
{
    try
    {
        this.querySocket = new DatagramSocket(this.queryPort, InetAddress.getByName(this.serverHostname));
        this.registerSocket(this.querySocket);
        this.querySocket.setSoTimeout(500);
        return true;
    }
    catch (SocketException socketexception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (Socket): " + socketexception.getMessage());
    }
    catch (UnknownHostException unknownhostexception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (Unknown Host): " + unknownhostexception.getMessage());
    }
    catch (Exception exception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (E): " + exception.getMessage());
    }

    return false;
}
项目:FinalSpeed    文件:CapEnv.java   
private void detectMac_udp(){
    for(int i=0;i<10;i++){
        try {
            DatagramSocket ds=new DatagramSocket();
            DatagramPacket dp=new DatagramPacket(new byte[1000], 1000);
            dp.setAddress(InetAddress.getByName(testIp_udp));
            dp.setPort(5555);
            ds.send(dp);
            ds.close();
            Thread.sleep(500);
            if(local_mac!=null){
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

}
项目:gnirehtet    文件:Forwarder.java   
/**
 * Neither vpnInterface.close() nor vpnInputStream.close() wake up a blocking
 * vpnInputStream.read().
 * <p>
 * Therefore, we need to make Android send a packet to the VPN interface (here by sending a UDP
 * packet), so that any blocking read will be woken up.
 * <p>
 * Since the tunnel is closed at this point, it will never reach the network.
 */
private void wakeUpReadWorkaround() {
    // network actions may not be called from the main thread
    EXECUTOR_SERVICE.execute(new Runnable() {
        @Override
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket();
                InetAddress dummyAddr = InetAddress.getByAddress(DUMMY_ADDRESS);
                DatagramPacket packet = new DatagramPacket(new byte[0], 0, dummyAddr, DUMMY_PORT);
                socket.send(packet);
            } catch (IOException e) {
                // ignore
            }
        }
    });
}
项目:LivroJavaComoProgramar10Edicao    文件:Server.java   
public Server()
{
   super("Server");

   displayArea = new JTextArea(); // create displayArea
   add(new JScrollPane(displayArea), BorderLayout.CENTER);
   setSize(400, 300); // set size of window
   setVisible(true); // show window

   try // create DatagramSocket for sending and receiving packets
   {
      socket = new DatagramSocket(5000);
   } 
   catch (SocketException socketException) 
   {
      socketException.printStackTrace();
      System.exit(1);
   } 
}
项目:LanChatLite    文件:Utils.java   
public static void sendUdpMsg(String msg, String ip, int port) {
  try {

    InetAddress address = InetAddress.getByName(ip);

    // Initialize a datagram packet with data and address
    DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), address, port);

    // Create a datagram socket, send the packet through it, close it.
    DatagramSocket dsocket = new DatagramSocket();
    dsocket.send(packet);
    dsocket.close();
  } catch (Exception e) {
    System.err.println(e);
  }
}
项目:cordova-plugin-smartconfig    文件:UDPSocketServer.java   
/**
 * Constructor of UDP Socket Server
 * 
 * @param port
 *            the Socket Server port
 * @param socketTimeout
 *            the socket read timeout
 * @param context
 *            the context of the Application
 */
public UDPSocketServer(int port, int socketTimeout, Context context) {
    this.mContext = context;
    this.buffer = new byte[64];
    this.mReceivePacket = new DatagramPacket(buffer, 64);
    try {
        this.mServerSocket = new DatagramSocket(port);
        this.mServerSocket.setSoTimeout(socketTimeout);
        this.mIsClosed = false;
        WifiManager manager = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);
        mLock = manager.createMulticastLock("test wifi");
        Log.d(TAG, "mServerSocket is created, socket read timeout: "
                + socketTimeout + ", port: " + port);
    } catch (IOException e) {
        Log.e(TAG, "IOException");
        e.printStackTrace();
    }
}
项目:OpenJSharp    文件:SnmpRequestHandler.java   
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
项目:myqq    文件:UDP.java   
/**
 * 获取可用的端口号
 */
public void getMyUsefulPort()
{
    while(true)
    {
        try
        {
            // 实例化一个DatagramSocket
            socket = new DatagramSocket(myPort);
            break;
        }
        catch (SocketException e)
        {
            myPort++;
        }
    }
}
项目:Reer    文件:FileLockCommunicator.java   
public FileLockCommunicator(InetAddressFactory addressFactory) {
    this.addressFactory = addressFactory;
    try {
        socket = new DatagramSocket(0, addressFactory.getLocalBindingAddress());
    } catch (SocketException e) {
        throw throwAsUncheckedException(e);
    }
}
项目:hadoop    文件:RpcProgramNfs3.java   
public static RpcProgramNfs3 createRpcProgramNfs3(NfsConfiguration config,
    DatagramSocket registrationSocket, boolean allowInsecurePorts)
    throws IOException {
  DefaultMetricsSystem.initialize("Nfs3");
  String displayName = DNS.getDefaultHost("default", "default")
      + config.getInt(NfsConfigKeys.DFS_NFS_SERVER_PORT_KEY,
          NfsConfigKeys.DFS_NFS_SERVER_PORT_DEFAULT);
  metrics = Nfs3Metrics.create(config, displayName);
  return new RpcProgramNfs3(config, registrationSocket, allowInsecurePorts);
}
项目:litiengine    文件:UdpPacketSender.java   
/**
 * Instantiates a new udp packet sender.
 */
public UdpPacketSender() {
  try {
    this.socket = new DatagramSocket();
  } catch (final SocketException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
项目:n4js    文件:HttpServerManagerTest.java   
private boolean isRunning(final int port) {
    if (0 > port || 65535 < port) {
        throw new IllegalArgumentException("Invalid port number: " + port);
    }
    try (final ServerSocket ss = new ServerSocket(port); final DatagramSocket ds = new DatagramSocket(port)) {
        ss.setReuseAddress(true);
        ds.setReuseAddress(true);
        return false;
    } catch (final IOException e) {
        return true;
    }
}
项目:gree-remote    文件:AsyncCommunicator.java   
private boolean createSocket() {
    try {
        mSocket = new DatagramSocket(new InetSocketAddress(DATAGRAM_PORT));
    } catch (SocketException e) {
        Log.e(LOG_TAG, "Failed to create socket. Error: " + e.getMessage());
        return false;
    }

    return true;
}
项目:FlashLib    文件:UDPCommInterface.java   
/**
 * {@inheritDoc}
 */
@Override
public void setLocalAddress(InetAddress addr) {
    if (isConnected() || !isOpened()) return;

    disconnect();

    try {
        socket = new DatagramSocket(socket.getLocalPort(), addr);
    } catch (IOException e) {
        e.printStackTrace();
    }

}
项目:hadoop-oss    文件:TestGangliaSink.java   
@Test
public void testShouldCreateDatagramSocketByDefault() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .subset("test.sink.ganglia");

    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
项目:hadoop-oss    文件:TestGangliaSink.java   
@Test
public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .add("test.sink.ganglia.multicast", false)
            .subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
项目:hadoop-oss    文件:TestGangliaSink.java   
@Test
public void testShouldCreateMulticastSocket() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .add("test.sink.ganglia.multicast", true)
            .subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertTrue("Did not create MulticastSocket", socket != null && socket instanceof MulticastSocket);
    int ttl = ((MulticastSocket) socket).getTimeToLive();
    assertEquals("Did not set default TTL", 1, ttl);
}
项目:hadoop-oss    文件:TestStatsDMetrics.java   
@Test(timeout=3000)
public void testPutMetrics() throws IOException, InterruptedException {
  final StatsDSink sink = new StatsDSink();
  List<MetricsTag> tags = new ArrayList<MetricsTag>();
  tags.add(new MetricsTag(MsInfo.Hostname, "host"));
  tags.add(new MetricsTag(MsInfo.Context, "jvm"));
  tags.add(new MetricsTag(MsInfo.ProcessName, "process"));
  Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
  metrics.add(makeMetric("foo1", 1.25, MetricType.COUNTER));
  metrics.add(makeMetric("foo2", 2.25, MetricType.GAUGE));
  final MetricsRecord record =
      new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics);

  try (DatagramSocket sock = new DatagramSocket()) {
    sock.setReceiveBufferSize(8192);
    final StatsDSink.StatsD mockStatsD =
        new StatsD(sock.getLocalAddress().getHostName(),
            sock.getLocalPort());
    Whitebox.setInternalState(sink, "statsd", mockStatsD);
    final DatagramPacket p = new DatagramPacket(new byte[8192], 8192);
    sink.putMetrics(record);
    sock.receive(p);

    String result =new String(p.getData(), 0, p.getLength(),
        Charset.forName("UTF-8"));
    assertTrue(
        "Received data did not match data sent",
        result.equals("host.process.jvm.Context.foo1:1.25|c") ||
        result.equals("host.process.jvm.Context.foo2:2.25|g"));

  } finally {
    sink.close();
  }
}
项目:africastalking-android    文件:NetworkUtils.java   
static String determineLocalIp() {
    try {
        DatagramSocket s = new DatagramSocket();
        s.connect(InetAddress.getByName("192.168.1.1"), 80);
        return s.getLocalAddress().getHostAddress();
    } catch (IOException e) {
        Log.e("determineLocalIp()", e.getMessage() + "");
        // dont do anything; there should be a connectivity change going
        return null;
    }
}
项目:EasyPeasyVPN    文件:MediationConnector.java   
public String getAccessibleNetworkAddressAtMediator(String networkName, Mediator mediator) {

        // TODO: Remove as soon as mediation is working..
        if (true) {
            return "0:0";
        }

        try {
            DatagramSocket clientSocket = new DatagramSocket();
            byte[] sendData = ("JOIN:" + networkName).getBytes("UTF-8");
            DatagramPacket sendPacket = new DatagramPacket(sendData,
                    sendData.length, InetAddress.getByName(mediator.getUrl()), Constants.MEDIATION_SERVER_PORT);
            clientSocket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
            clientSocket.receive(receivePacket);
            String response = new String(receivePacket.getData());
            response = NetworkUtilities.getCleanString(response);
            System.out.println("Response: " + response);
            if(response.equals("ERROR"))
                return null;
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
项目:sonos-remote-things    文件:SSDPClient.java   
/**
 * Discover any UPNP device using SSDP (Simple Service Discovery Protocol).
 * @param timeout in milliseconds
 * @param serviceType if null it use "ssdp:all"
 * @return List of devices discovered
 * @throws IOException
 * @see <a href="https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol">SSDP Wikipedia Page</a>
 */
public static List<Device> discover(int timeout, String serviceType) throws IOException {
    ArrayList<Device> devices = new ArrayList<Device>();
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive all responses */
    while (true) {
        try {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
            devices.add(Device.parse(receivePacket));
        }
        catch (SocketTimeoutException e) { break; }
    }

    clientSocket.close();
    return Collections.unmodifiableList(devices);
}
项目:sonos-remote-things    文件:SSDPClient.java   
public static Device discoverOne(int timeout, String serviceType) throws IOException {
    Device device = null;
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive one response */
    try {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        device = Device.parse(receivePacket);
    }
    catch (SocketTimeoutException e) { }

    clientSocket.close();
    return device;
}
项目:hadoop    文件:SimpleUdpClient.java   
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();
    }
  }
}
项目:openNaEF    文件:SimulatedSnmpClientFactory.java   
public SnmpClient createSnmpClient(
        final InetAddress nodeAddress,
        SimulationEntry entry)
        throws IOException {
    if (nodeAddress == null) {
        throw new IOException("nodeAddress == null");
    }
    if (archive == null) {
        throw new IOException("archive is null");
    }
    if (!archive.exists(nodeAddress.getHostAddress())) {
        throw new IOException("no simulationEntry found: " + nodeAddress.getHostAddress());
    }
    DatagramSocket socket = new DatagramSocket();
    final SnmpAgentEmulator agentEmulator =
            new SnmpAgentEmulator(
                    new ZipFile(archive.getSimulationArchiveFile()),
                    entry.getMibZipEntryName(),
                    socket);
    agentEmulator.start();
    return new SnmpClient(
            InetAddress.getLocalHost(),
            socket.getLocalPort(),
            "public".getBytes(),
            new SnmpClientLogger()) {
        public void close() {
            try {
                agentEmulator.stop();
            } catch (Exception e) {
                log.info(e.toString());
            }
        }

        public InetSocketAddress getSnmpAgentAddress() {
            return new InetSocketAddress(nodeAddress, 0);
        }
    };
}