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

The following examples show how to use java.net.DatagramSocket#close() . 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: AvailablePortFinder.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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
 */
private boolean available(int port) {
    try {
        ServerSocket ss = new ServerSocket(port);
        try {
            ss.setReuseAddress(true);
        } finally {
            ss.close();
        }
        DatagramSocket ds = new DatagramSocket(port);
        try {
            ds.setReuseAddress(true);
        } finally {
            ds.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 2
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for 'DatagramChannelImpl.socket()'
 */
public void testSocket_ActionsBeforeConnect() throws IOException {
    assertFalse(channel1.isConnected());// not connected
    assertTrue(channel1.isBlocking());
    DatagramSocket s = channel1.socket();

    s.connect(datagramSocket2Address);
    assertTrue(channel1.isConnected());
    assertTrue(s.isConnected());

    s.disconnect();
    assertFalse(channel1.isConnected());
    assertFalse(s.isConnected());

    s.close();
    assertTrue(s.isClosed());
    assertFalse(channel1.isOpen());
}
 
Example 3
Source File: AutoStop.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
private void stopTestViaUDP(String command) {
    try {
        int port = JMeterUtils.getPropDefault("jmeterengine.nongui.port", JMeter.UDP_PORT_DEFAULT);
        log.info("Sending " + command + " request to port " + port);
        DatagramSocket socket = new DatagramSocket();
        byte[] buf = command.getBytes("ASCII");
        InetAddress address = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
        socket.close();
    } catch (Exception e) {
        //e.printStackTrace();
        log.error(e.getMessage());
    }

}
 
Example 4
Source File: UpnpSettingsResource.java    From ha-bridge with Apache License 2.0 6 votes vote down vote up
private InetAddress getOutboundAddress(String remoteAddress, int remotePort) {
	InetAddress localAddress = null;
	try {
	DatagramSocket sock = new DatagramSocket();
	// connect is needed to bind the socket and retrieve the local address
	// later (it would return 0.0.0.0 otherwise)
	sock.connect(new InetSocketAddress(remoteAddress, remotePort));
	localAddress = sock.getLocalAddress();
	sock.disconnect();
	sock.close();
	sock = null;
	} catch(Exception e)  {
		ParseRoute theRoute = ParseRoute.getInstance();
		try {
			localAddress = InetAddress.getByName(theRoute.getLocalIPAddress());
		} catch(Exception e1) {}
		log.warn("Error <" + e.getMessage() + "> on determining interface to reply for <" + remoteAddress + ">. Using default route IP Address of " + localAddress.getHostAddress());
	}
	log.debug("getOutbountAddress returning IP Address of " + localAddress.getHostAddress());
	return localAddress;
}
 
Example 5
Source File: TestCaseSupport.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private void startUDPServer() throws UnknownHostException, InterruptedException {
    udpListener = new ModbusUDPListener(localAddress(), udpTerminalFactory);
    for (int portCandidate = 10000 + udpServerIndex.increment(); portCandidate < 20000; portCandidate++) {
        try {
            DatagramSocket socket = new DatagramSocket(portCandidate);
            socket.close();
            udpListener.setPort(portCandidate);
            break;
        } catch (SocketException e) {
            continue;
        }
    }

    udpListener.start();
    waitForUDPServerStartup();
    Assert.assertNotSame(-1, udpModbusPort);
    Assert.assertNotSame(0, udpModbusPort);
}
 
Example 6
Source File: SyslogAppenderTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String[] log(final boolean header,
                            final String msg,
                            final Exception ex,
                            final int packets) throws Exception {
    DatagramSocket ds = new DatagramSocket();
    ds.setSoTimeout(2000);

  SyslogAppender appender = new SyslogAppender();
  appender.setSyslogHost("localhost:" + ds.getLocalPort());
  appender.setName("name");
  appender.setHeader(header);
  PatternLayout pl = new PatternLayout("%m");
  appender.setLayout(pl);
  appender.activateOptions();

  Logger l = Logger.getRootLogger();
  l.addAppender(appender);
  if (ex == null) {
    l.info(msg);
  } else {
    l.error(msg, ex);
  }
  appender.close();
  String[] retval = new String[packets];
  byte[] buf = new byte[1000];
  for(int i = 0; i < packets; i++) {
      DatagramPacket p = new DatagramPacket(buf, 0, buf.length);
      ds.receive(p);
      retval[i] = new String(p.getData(), 0, p.getLength());
  }
  ds.close();
  return retval;
}
 
Example 7
Source File: AcceptorTest.java    From game-server with MIT License 5 votes vote down vote up
public void testUDP() throws Exception {
	DatagramSocket client = new DatagramSocket();
	client.connect(new InetSocketAddress("127.0.0.1", port));
	client.setSoTimeout(500);

	byte[] writeBuf = new byte[16];
	byte[] readBuf = new byte[writeBuf.length];
	DatagramPacket wp = new DatagramPacket(writeBuf, writeBuf.length);
	DatagramPacket rp = new DatagramPacket(readBuf, readBuf.length);

	for (int i = 0; i < 10; i++) {
		fillWriteBuffer(writeBuf, i);
		client.send(wp);

		client.receive(rp);
		assertEquals(writeBuf.length, rp.getLength());
		assertTrue(Arrays.equals(writeBuf, readBuf));
	}

	try {
		client.receive(rp);
		fail("Unexpected incoming data.");
	} catch (SocketTimeoutException e) {
	}

	client.close();
}
 
Example 8
Source File: PortManager.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isPortFree(int port) {
  if (port <= 0) {
    return false;
  }
  try {
    DatagramSocket udpSocket = new DatagramSocket(port);
    udpSocket.close();
    return true;
  } catch (IOException ioe) {
    return false;
  }
}
 
Example 9
Source File: UDPReceiverTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void sendSocketBufferSize() throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

    datagramSocket.send(datagramPacket);
    datagramSocket.close();
}
 
Example 10
Source File: SyslogSourceTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
protected void sendUdp(String syslog) throws Exception {
	waitUdp();
	DatagramSocket socket = new DatagramSocket();
	DatagramPacket packet = new DatagramPacket(syslog.getBytes(), syslog.length());
	packet.setSocketAddress(new InetSocketAddress("localhost", this.port));
	socket.send(packet);
	socket.close();
}
 
Example 11
Source File: SyslogClient.java    From freeacs with MIT License 5 votes vote down vote up
public static void send(String msg) throws IOException {
  DatagramSocket socket = new DatagramSocket();
  byte[] message = msg.getBytes(StandardCharsets.UTF_8);
  DatagramPacket packet = new DatagramPacket(message, message.length);
  InetAddress address = InetAddress.getByName(SYSLOG_SERVER_HOST);
  packet.setPort(9116);
  packet.setAddress(address);
  socket.send(packet);
  socket.close();
}
 
Example 12
Source File: JGroupMembershipManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseQuorumChecker(QuorumChecker checker) {
  ((QuorumCheckerImpl)checker).teardown();
  InternalDistributedSystem system = InternalDistributedSystem.getAnyInstance();
  if (system == null || !system.isConnected()) {
    DatagramSocket sock = (DatagramSocket)checker.getMembershipInfo();
    if (sock != null  &&  !sock.isClosed()) {
      sock.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: UDPTestServer.java    From java-tcp-tunnel with MIT License 5 votes vote down vote up
public void runrun() throws Exception {
  DatagramSocket server = new DatagramSocket(port);
  DatagramPacket pkt = new DatagramPacket(receiveBuffer, receiveBuffer.length);
  System.out.println("UDP test server listening on port "+port);
  started = true; //still could race but rather small chance and its just for testing
  server.receive(pkt);
  bytesReceived = pkt.getLength();
  System.out.println("UDP test server received "+bytesReceived+" bytes, exiting.");
  server.close();
}
 
Example 15
Source File: NetworkPackageQueueHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
private void send(NetworkPackage networkPackage) throws Exception {
    switch (networkPackage.getCommunicationType()) {
        case UDP:
            InetAddress host = InetAddress.getByName(networkPackage.getHost());
            int port = networkPackage.getPort();

            socket = new DatagramSocket(null);
            socket.setReuseAddress(true);
            socket.connect(host, port);

            byte[] messageBuffer = networkPackage.getMessage().getBytes();
            DatagramPacket messagePacket = new DatagramPacket(messageBuffer, messageBuffer.length, host, port);
            socket.send(messagePacket);

            Log.d("UDP Sender", "Host: " + host.getHostAddress() + ":" + port
                    + " Message: \"" + new String(messageBuffer) + "\" sent.");

            socket.disconnect();
            socket.close();
            break;
        case HTTP:
            URL url = new URL("http://" + networkPackage.getHost() + ":" + networkPackage.getPort() + "/" +
                    networkPackage.getMessage());
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);
            } finally {
                urlConnection.disconnect();
            }
            break;
    }
}
 
Example 16
Source File: UDPTestClient.java    From sockslib with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  DatagramSocket clientSocket = new DatagramSocket();
  String message = "Hello, UDP server";
  DatagramPacket buffer =
      new DatagramPacket(message.getBytes(), message.length(), new InetSocketAddress("0.0.0.0",
          5050));
  clientSocket.send(buffer);
  clientSocket.close();
}
 
Example 17
Source File: HelloUdpServerExternalResource.java    From ribbon with Apache License 2.0 4 votes vote down vote up
private int choosePort() throws SocketException {
    DatagramSocket serverSocket = new DatagramSocket();
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;
}
 
Example 18
Source File: MaxRetries.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    System.setProperty("sun.security.krb5.debug", "true");
    new OneKDC(null).writeJAASConf();

    // An idle UDP socket to revent PortUnreachableException
    DatagramSocket ds = new DatagramSocket(33333);

    System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");

    // For tryLast
    Security.setProperty("krb5.kdc.bad.policy", "trylast");
    rewriteMaxRetries(4);
    test1(4000, 6);         // 1 1 1 1 2 2
    test1(4000, 2);         // 2 2

    rewriteMaxRetries(1);
    test1(1000, 3);         // 1 2 2
    test1(1000, 2);         // 2 2

    rewriteMaxRetries(-1);
    test1(5000, 4);         // 1 1 2 2
    test1(5000, 2);         // 2 2

    // For tryLess
    Security.setProperty("krb5.kdc.bad.policy", "tryless");
    rewriteMaxRetries(4);
    test1(4000, 7);         // 1 1 1 1 2 1 2
    test1(4000, 4);         // 1 2 1 2

    rewriteMaxRetries(1);
    test1(1000, 4);         // 1 2 1 2
    test1(1000, 4);         // 1 2 1 2

    rewriteMaxRetries(-1);
    test1(5000, 5);         // 1 1 2 1 2
    test1(5000, 4);         // 1 2 1 2

    rewriteUdpPrefLimit(-1, -1);    // default, no limit
    test2("UDP");

    rewriteUdpPrefLimit(10, -1);    // global rules
    test2("TCP");

    rewriteUdpPrefLimit(10, 10000); // realm rules
    test2("UDP");

    rewriteUdpPrefLimit(10000, 10); // realm rules
    test2("TCP");

    ds.close();
}
 
Example 19
Source File: SocketUtils.java    From tilt-game-android with MIT License 4 votes vote down vote up
public static final void closeSocket(final DatagramSocket pDatagramSocket) {
	if (pDatagramSocket != null && !pDatagramSocket.isClosed()) {
		pDatagramSocket.close();
	}
}
 
Example 20
Source File: XRayUDPStorage.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
@Override public synchronized void close() {
  if (closeCalled) return;
  DatagramSocket socket = this.socket;
  if (socket != null) socket.close();
  closeCalled = true;
}