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

The following examples show how to use java.net.DatagramSocket#setReceiveBufferSize() . 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: UDPReceiver.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private DatagramSocket createSocket0(int receiveBufferSize) {
    try {
        DatagramSocket socket = new DatagramSocket(null);
        socket.setReceiveBufferSize(receiveBufferSize);
        if (logger.isWarnEnabled()) {
            final int checkReceiveBufferSize = socket.getReceiveBufferSize();
            if (receiveBufferSize != checkReceiveBufferSize) {
                logger.warn("DatagramSocket.setReceiveBufferSize() error. {}!={}", receiveBufferSize, checkReceiveBufferSize);
            }
        }
        socket.setSoTimeout(1000 * 5);
        return socket;
    } catch (SocketException ex) {
        throw new RuntimeException("Socket create Fail. Caused:" + ex.getMessage(), ex);
    }
}
 
Example 2
Source File: SyslogServer.java    From freeacs with MIT License 5 votes vote down vote up
private DatagramPacket initServer() {
  do {
    logger.info("Will try to bind server to port " + properties.getPort());
    try {
      socket = new DatagramSocket(properties.getPort());
      socket.setSoTimeout(SOCKET_TIMEOUT);
      socket.setReceiveBufferSize(properties.getReceiveBufferSize() * 1024);
      logger.info("Created a socket and bound to port " + properties.getPort());
      byte[] log_buffer = new byte[socket.getReceiveBufferSize()];
      logger.info("Created receive buffer, size " + log_buffer.length / 1024 + " KB");
      DatagramPacket packet = new DatagramPacket(log_buffer, log_buffer.length);
      FailoverFileReader failoverFileReader = new FailoverFileReader(properties);
      Thread failoverFileReaderThread = new Thread(failoverFileReader);
      failoverFileReaderThread.setName("FailoverFileReader");
      failoverFileReaderThread.start();
      logger.info(
          "Created FailoverFileReader thread to read from any failover files created by the syslog server");
      return packet;
    } catch (Throwable t) {
      throwable = t;
      ok = false;
      if (!Sleep.isTerminated()) {
        logger.error("Error occured, server did not start, will try again in 60 sec", t);
      } else {
        break;
      }
      try {
        Thread.sleep(60000); // Try again in 60 sec
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  } while (true);
  return null; // unreachable code
}
 
Example 3
Source File: StunServer.java    From freeacs with MIT License 5 votes vote down vote up
public void start() throws SocketException {
  int counter = 0;
  for (DatagramSocket socket : sockets) {
    socket.setReceiveBufferSize(2000);
    StunServerReceiverThread ssrt;
    ssrt = new StunServerReceiverThread(socket, counter == 0);
    ssrt.setName("StunServerReceiverThread-" + counter);
    counter++;
    ssrt.start();
  }
}
 
Example 4
Source File: Config.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static void getConfigForUDPSocket(DatagramSocket socket) throws Exception
  {
int receiveBuffer = Config.getConfigByName("udp.properties").getInteger("socket.RECEIVE_BUFFER", 8192);
socket.setReceiveBufferSize(receiveBuffer);
boolean reuseAddress = Config.getConfigByName("udp.properties").getBoolean("socket.REUSE_ADDRESS", false);
socket.setReuseAddress(reuseAddress);
int sendBuffer = Config.getConfigByName("udp.properties").getInteger("socket.SEND_BUFFER", 8192);
socket.setSendBufferSize(sendBuffer);
int timeout = Config.getConfigByName("udp.properties").getInteger("socket.TIMEOUT", 0);
socket.setSoTimeout(timeout);
int trafficClass = Config.getConfigByName("udp.properties").getInteger("socket.TRAFFIC_CLASS", 0);
socket.setTrafficClass(trafficClass);
  }
 
Example 5
Source File: UdpSocket.java    From AndroidUtils with The Unlicense 5 votes vote down vote up
/**
 * Constructs a UDP datagram socket which is bound to the specific port with
 * socket buffer size set.
 *
 * @param port the port to bind on the localhost.
 * @param size this socket's send and recv buffer size.
 */
public UdpSocket(int port, int size) {
    super();
    try {
        this.port = port;
        socket = new DatagramSocket(port);
        socket.setSendBufferSize(size);
        socket.setReceiveBufferSize(size);
    } catch (SocketException e) {
        e.printStackTrace();
        udpEnd();
    }
}
 
Example 6
Source File: UDPConnection.java    From jlibs with Apache License 2.0 5 votes vote down vote up
protected void init() throws IOException{
    DatagramSocket socket = selectable.socket();
    if(SO_SNDBUF!=null)
        socket.setSendBufferSize(SO_SNDBUF);
    if(SO_RCVBUF!=null)
        socket.setReceiveBufferSize(SO_RCVBUF);
}
 
Example 7
Source File: UDPReceiverTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void socketBufferSize() throws SocketException {
    DatagramSocket datagramSocket = new DatagramSocket();
    int receiveBufferSize = datagramSocket.getReceiveBufferSize();
    logger.debug("{}", receiveBufferSize);

    datagramSocket.setReceiveBufferSize(64 * 1024 * 10);
    logger.debug("{}", datagramSocket.getReceiveBufferSize());

    datagramSocket.close();
}
 
Example 8
Source File: ServerInfoTask.java    From Plumble with GNU General Public License v3.0 5 votes vote down vote up
@Override
	protected ServerInfoResponse doInBackground(Server... params) {
		server = params[0];
		try {
			InetAddress host = InetAddress.getByName(server.getHost());
			
			// Create ping message
			ByteBuffer buffer = ByteBuffer.allocate(12);
			buffer.putInt(0); // Request type
			buffer.putLong(server.getId()); // Identifier
			DatagramPacket requestPacket = new DatagramPacket(buffer.array(), 12, host, server.getPort());
			
			// Send packet and wait for response
			DatagramSocket socket = new DatagramSocket();
			socket.setSoTimeout(1000);
			socket.setReceiveBufferSize(1024);

            long startTime = System.nanoTime();

            socket.send(requestPacket);
			
			byte[] responseBuffer = new byte[24];
			DatagramPacket responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length);
			socket.receive(responsePacket);

            int latencyInMs = (int) ((System.nanoTime()-startTime)/1000000);
			
			ServerInfoResponse response = new ServerInfoResponse(server, responseBuffer, latencyInMs);
							
			Log.i(Constants.TAG, "DEBUG: Server version: "+response.getVersionString()+"\nUsers: "+response.getCurrentUsers()+"/"+response.getMaximumUsers());
			
			return response;
			
		} catch (Exception e) {
//			e.printStackTrace();
		}

		return new ServerInfoResponse(); // Return dummy in case of failure
	}
 
Example 9
Source File: UdpSocket.java    From libcommon with Apache License 2.0 4 votes vote down vote up
public void setReceiveBufferSize(final int sz) throws SocketException {
	final DatagramSocket socket = channel != null ? channel.socket() : null;
	if (socket != null) {
		socket.setReceiveBufferSize(sz);
	}
}
 
Example 10
Source File: UdpKoupler.java    From koupler with MIT License 4 votes vote down vote up
public UdpKoupler(KinesisEventProducer producer, int port) throws SocketException {
    super(producer, 1);
    LOGGER.info("Firing up UDP listener on [{}]", port);
    socket = new DatagramSocket(port);
    socket.setReceiveBufferSize(1024 * 1024 * 1024);
}
 
Example 11
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());
}