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

The following examples show how to use java.net.DatagramSocket#isClosed() . 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: ReuseAddressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
String getInfo(DatagramSocket soc) {
    if (soc == null) {
        return null;
    }

    return "localPort: " + soc.getLocalPort()
            + "; localAddress: " + soc.getLocalAddress()
            + "; remotePort: " + soc.getPort()
            + "; remoteAddress: " + soc.getInetAddress()
            + "; isClosed: " + soc.isClosed()
            + "; isBound: " + soc.isBound();
}
 
Example 2
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 3
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 4
Source File: SocketTagger.java    From AndroidComponentPlugin with Apache License 2.0 4 votes vote down vote up
public final void tag(DatagramSocket socket) throws SocketException {
    if (!socket.isClosed()) {
        tag(socket.getFileDescriptor$());
    }
}
 
Example 5
Source File: SocketTagger.java    From AndroidComponentPlugin with Apache License 2.0 4 votes vote down vote up
public final void untag(DatagramSocket socket) throws SocketException {
    if (!socket.isClosed()) {
        untag(socket.getFileDescriptor$());
    }
}
 
Example 6
Source File: JDASendSystem.java    From andesite-node with MIT License 4 votes vote down vote up
@Override
public void start() {
    final DatagramSocket udpSocket = packetProvider.getUdpSocket();
    
    sendThread = new Thread(() -> {
        long lastFrameSent = System.currentTimeMillis();
        boolean sentPacket = true;
        while(!udpSocket.isClosed() && !sendThread.isInterrupted()) {
            try {
                boolean changeTalking = !sentPacket || (System.currentTimeMillis() - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT;
                DatagramPacket packet = packetProvider.getNextPacket(changeTalking);
                
                sentPacket = packet != null;
                if(sentPacket) {
                    udpSocket.send(packet);
                }
            } catch(NoRouteToHostException e) {
                //we can't call this as magma doesn't support it
                //packetProvider.onConnectionLost();
                break;
            } catch(SocketException e) {
                //Most likely the socket has been closed due to the audio connection be closed. Next iteration will kill loop.
            } catch(Exception e) {
                log.error("Error while sending udp audio data", e);
            } finally {
                long sleepTime = (OPUS_FRAME_TIME_AMOUNT) - (System.currentTimeMillis() - lastFrameSent);
                if(sleepTime > 0) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch(InterruptedException e) {
                        //We've been asked to stop.
                        Thread.currentThread().interrupt();
                    }
                }
                if(System.currentTimeMillis() < lastFrameSent + 60) {
                    // If the sending didn't took longer than 60ms (3 times the time frame)
                    lastFrameSent += OPUS_FRAME_TIME_AMOUNT;
                } else {
                    // else reset lastFrameSent to current time
                    lastFrameSent = System.currentTimeMillis();
                }
            }
        }
    });
    sendThread.setUncaughtExceptionHandler((thread, throwable) -> {
        log.error("Uncaught exception in audio send thread", throwable);
        start();
    });
    sendThread.setDaemon(true);
    //we can't call getIdentifier() as magma doesn't support it either, so just use the toString there
    sendThread.setName(packetProvider + " Sending Thread");
    sendThread.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
    sendThread.start();
}
 
Example 7
Source File: DefaultSendSystem.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
public void start()
{
    final DatagramSocket udpSocket = packetProvider.getUdpSocket();

    sendThread = new Thread(() ->
    {
        if (contextMap != null)
            MDC.setContextMap(contextMap);
        long lastFrameSent = System.currentTimeMillis();
        boolean sentPacket = true;
        while (!udpSocket.isClosed() && !sendThread.isInterrupted())
        {
            try
            {
                boolean changeTalking = !sentPacket || (System.currentTimeMillis() - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT;
                DatagramPacket packet = packetProvider.getNextPacket(changeTalking);

                sentPacket = packet != null;
                if (sentPacket)
                    udpSocket.send(packet);
            }
            catch (NoRouteToHostException e)
            {
                packetProvider.onConnectionLost();
            }
            catch (SocketException e)
            {
                //Most likely the socket has been closed due to the audio connection be closed. Next iteration will kill loop.
            }
            catch (Exception e)
            {
                AudioConnection.LOG.error("Error while sending udp audio data", e);
            }
            finally
            {
                long sleepTime = (OPUS_FRAME_TIME_AMOUNT) - (System.currentTimeMillis() - lastFrameSent);
                if (sleepTime > 0)
                {
                    try
                    {
                        Thread.sleep(sleepTime);
                    }
                    catch (InterruptedException e)
                    {
                        //We've been asked to stop.
                        Thread.currentThread().interrupt();
                    }
                }
                if (System.currentTimeMillis() < lastFrameSent + 60)
                {
                    // If the sending didn't took longer than 60ms (3 times the time frame)
                    lastFrameSent += OPUS_FRAME_TIME_AMOUNT;
                }
                else
                {
                    // else reset lastFrameSent to current time
                    lastFrameSent = System.currentTimeMillis();
                }
            }
        }
    });
    sendThread.setUncaughtExceptionHandler((thread, throwable) ->
    {
        JDALogger.getLog(DefaultSendSystem.class).error("Uncaught exception in audio send thread", throwable);
        start();
    });
    sendThread.setDaemon(true);
    sendThread.setName(packetProvider.getIdentifier() + " Sending Thread");
    sendThread.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
    sendThread.start();
}
 
Example 8
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 9
Source File: SocketTagger.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public final void tag(DatagramSocket socket) throws SocketException {
    if (!socket.isClosed()) {
        tag(socket.getFileDescriptor$());
    }
}
 
Example 10
Source File: SocketTagger.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public final void untag(DatagramSocket socket) throws SocketException {
    if (!socket.isClosed()) {
        untag(socket.getFileDescriptor$());
    }
}
 
Example 11
Source File: SocketUtils.java    From 30-android-libraries-in-30-days with Apache License 2.0 4 votes vote down vote up
public static final void closeSocket(final DatagramSocket pDatagramSocket) {
	if(pDatagramSocket != null && !pDatagramSocket.isClosed()) {
		pDatagramSocket.close();
	}
}
 
Example 12
Source File: UdpManager.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 启动服务. 可以指定地址和端口
 */
public synchronized void start(SocketAddress addr) throws IOException
{
	if (isRunning())
		throw new IllegalStateException(name + " has already started");

	final DatagramSocket s = new DatagramSocket(addr != null ? addr : new InetSocketAddress(0));
	s.setReceiveBufferSize(SOCKET_RECV_BUFFER_SIZE);
	s.setSendBufferSize(SOCKET_SEND_BUFFER_SIZE);
	socket = s;

	receiveThread = new Thread(name + "-ReceiveThread")
	{
		@Override
		public void run()
		{
			final String threadName = Thread.currentThread().getName();
			Log.info("{} started", threadName);
			try
			{
				for (;;)
				{
					try
					{
						if (s.isClosed())
							break;
						final DatagramPacket packet = allocPacket();
						s.receive(packet); // 当前socket缓冲区为空时会阻塞. 返回时会为packet设置地址. 出错时会抛各种异常
						onReceive(packet); // 业务处理可能会抛各种异常
					}
					catch (InterruptedException e)
					{
						throw e;
					}
					catch (Throwable e)
					{
						Log.error(e, "{} exception:", threadName);
						Thread.sleep(1); // 避免频繁出错
					}
				}
			}
			catch (InterruptedException interruptedException)
			{
				Log.info("{} interrupted", threadName);
			}
			finally
			{
				Log.info("{} stopped", threadName);
			}
		}
	};
	receiveThread.start();

	Log.info("{}({}): started", name, s.getLocalSocketAddress());
}