Java Code Examples for java.net.Socket#setReuseAddress()

The following examples show how to use java.net.Socket#setReuseAddress() . 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: Networking.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static boolean isReachable(HostAndPort endpoint, boolean noReuseOrLinger, int timeout) {
    try {
        Socket s = new Socket();
        if (noReuseOrLinger) {
            s.setReuseAddress(false);
            s.setSoLinger(false, 1);
        }
        if (timeout>0) {
            s.setSoTimeout(timeout);
        }
        s.connect(new InetSocketAddress(endpoint.getHostText(), endpoint.getPort()), timeout);
        closeQuietly(s);
        return true;
    } catch (Exception e) {
        if (log.isTraceEnabled()) log.trace("Error reaching "+endpoint+" during reachability check (return false)", e);
        return false;
    }
}
 
Example 2
Source File: UtilsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getSocketOptions() throws Exception {
  Socket socket = new Socket();
  socket.setSoLinger(true, 2);
  socket.setSoTimeout(3);
  socket.setTcpNoDelay(true);
  socket.setReuseAddress(true);
  socket.setReceiveBufferSize(4000);
  socket.setSendBufferSize(5000);
  socket.setKeepAlive(true);
  socket.setOOBInline(true);
  socket.setTrafficClass(8); // note: see javadoc for valid input values

  SocketOptions socketOptions = Utils.getSocketOptions(socket);
  assertEquals(2, (int) socketOptions.lingerSeconds);
  assertEquals(3, (int) socketOptions.soTimeoutMillis);
  assertEquals("true", socketOptions.others.get("TCP_NODELAY"));
  assertEquals("true", socketOptions.others.get("SO_REUSEADDR"));
  assertEquals("4000", socketOptions.others.get("SO_RECVBUF"));
  assertEquals("5000", socketOptions.others.get("SO_SNDBUF"));
  assertEquals("true", socketOptions.others.get("SO_KEEPALIVE"));
  assertEquals("true", socketOptions.others.get("SO_OOBINLINE"));
  assertEquals("8", socketOptions.others.get("IP_TOS"));
}
 
Example 3
Source File: SocketProperties.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public void setProperties(Socket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (txBufSize != null)
        socket.setSendBufferSize(txBufSize.intValue());
    if (ooBInline !=null)
        socket.setOOBInline(ooBInline.booleanValue());
    if (soKeepAlive != null)
        socket.setKeepAlive(soKeepAlive.booleanValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soLingerOn != null && soLingerTime != null)
        socket.setSoLinger(soLingerOn.booleanValue(),
                soLingerTime.intValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
    if (tcpNoDelay != null)
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
 
Example 4
Source File: EpollReuseAddrTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10000)
public void testMultipleBindSocketChannel() throws Exception {
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    ServerBootstrap bootstrap = createServerBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean accepted1 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();

    final AtomicBoolean accepted2 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted2));
    ChannelFuture future2 = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();

    Assert.assertEquals(address1, address2);
    while (!accepted1.get() || !accepted2.get()) {
        Socket socket = new Socket(address1.getAddress(), address1.getPort());
        socket.setReuseAddress(true);
        socket.close();
    }
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
}
 
Example 5
Source File: EpollReuseAddrTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10000)
public void testMultipleBindSocketChannel() throws Exception {
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    ServerBootstrap bootstrap = createServerBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean accepted1 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();

    final AtomicBoolean accepted2 = new AtomicBoolean();
    bootstrap.childHandler(new ServerSocketTestHandler(accepted2));
    ChannelFuture future2 = bootstrap.bind(address1).syncUninterruptibly();
    InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();

    Assert.assertEquals(address1, address2);
    while (!accepted1.get() || !accepted2.get()) {
        Socket socket = new Socket(address1.getAddress(), address1.getPort());
        socket.setReuseAddress(true);
        socket.close();
    }
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
}
 
Example 6
Source File: BaseWssSocketBuilder.java    From Java-OCA-OCPP with MIT License 6 votes vote down vote up
@Override
public Socket build() throws IOException {
  verify(true);

  Socket socket = socketFactory.getSocket(proxy);
  socket.setTcpNoDelay(tcpNoDelay);
  socket.setReuseAddress(reuseAddr);

  if (!socket.isBound()) {
    socket.connect(
        inetSocketAddressFactory.getInetSocketAddress(uri.getHost(), getPort(uri)),
        connectionTimeout);
  }

  return sslSocketFactory.createSocket(socket, uri.getHost(), getPort(uri), autoClose);
}
 
Example 7
Source File: MultiplayerClient.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialize the SocketClient up to and including issuing the accept()
 * method on its socketConnection.
 *
 * @throws java.net.SocketException
 */
protected void initSocketConnection() throws SocketException {
	try {
		sock = new Socket();
		/*
		 * Allows the socket to be bound even though a previous connection
		 * is in a timeout state.
		 */
		sock.setReuseAddress(true);
		/*
		 * Create a socket connection to the server
		 */
		sock.connect(new InetSocketAddress(serverAddressStr, PORT));
		// if (debugFlagIsSet(Constants.instance().DEBUG_STATUS)) {
		// System.out.println("Connected to " + host
		// + "at port " + port);
		// }
	} catch (IOException e) {
		// if (debugFlagIsSet(Constants.instance().DEBUG_EXCEPTIONS)) {
		e.printStackTrace();
		// }
		throw new SocketException();
	}
}
 
Example 8
Source File: TCPNetSyslogWriter.java    From syslog4j-graylog2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected Socket createSocket(InetAddress hostAddress, int port, boolean keepalive) throws IOException {
    SocketFactory socketFactory = obtainSocketFactory();

    Socket newSocket = socketFactory.createSocket(hostAddress, port);

    if (this.tcpNetSyslogConfig.isSoLinger()) {
        newSocket.setSoLinger(true, this.tcpNetSyslogConfig.getSoLingerSeconds());
    }

    if (this.tcpNetSyslogConfig.isKeepAlive()) {
        newSocket.setKeepAlive(keepalive);
    }

    if (this.tcpNetSyslogConfig.isReuseAddress()) {
        newSocket.setReuseAddress(true);
    }

    return newSocket;
}
 
Example 9
Source File: TCPMasterConnection.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens this <tt>TCPMasterConnection</tt>.
 *
 * @throws Exception if there is a network failure.
 */
@Override
public synchronized boolean connect() throws Exception {
    if (!isConnected()) {
        logger.debug("connect()");
        m_Socket = new Socket();
        m_Socket.connect(new InetSocketAddress(m_Address, m_Port), this.m_ConnectTimeoutMillis);
        setTimeout(m_Timeout);
        m_Socket.setReuseAddress(true);
        m_Socket.setSoLinger(true, 1);
        m_Socket.setKeepAlive(true);
        prepareTransport();
        m_Connected = true;
    }
    return m_Connected;
}
 
Example 10
Source File: BioReceiver.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public void listen() throws Exception {
    if (doListen()) {
        log.warn("ServerSocket already started");
        return;
    }
    setListen(true);

    while ( doListen() ) {
        Socket socket = null;
        if ( getTaskPool().available() < 1 ) {
            if ( log.isWarnEnabled() )
                log.warn("All BIO server replication threads are busy, unable to handle more requests until a thread is freed up.");
        }
        BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask();
        if ( task == null ) continue; //should never happen
        try {
            socket = serverSocket.accept();
        }catch ( Exception x ) {
            if ( doListen() ) throw x;
        }
        if ( !doListen() ) {
            task.setDoRun(false);
            task.serviceSocket(null,null);
            getExecutor().execute(task);
            break; //regular shutdown
        }
        if ( socket == null ) continue;
        socket.setReceiveBufferSize(getRxBufSize());
        socket.setSendBufferSize(getTxBufSize());
        socket.setTcpNoDelay(getTcpNoDelay());
        socket.setKeepAlive(getSoKeepAlive());
        socket.setOOBInline(getOoBInline());
        socket.setReuseAddress(getSoReuseAddress());
        socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
        socket.setSoTimeout(getTimeout());
        ObjectReader reader = new ObjectReader(socket);
        task.serviceSocket(socket,reader);
        getExecutor().execute(task);
    }//while
}
 
Example 11
Source File: BioReceiver.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void listen() throws Exception {
    if (doListen()) {
        log.warn(sm.getString("bioReceiver.already.started"));
        return;
    }
    setListen(true);

    while ( doListen() ) {
        Socket socket = null;
        if ( getTaskPool().available() < 1 ) {
            if ( log.isWarnEnabled() )
                log.warn(sm.getString("bioReceiver.threads.busy"));
        }
        BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask();
        if ( task == null ) continue; //should never happen
        try {
            socket = serverSocket.accept();
        }catch ( Exception x ) {
            if ( doListen() ) throw x;
        }
        if ( !doListen() ) {
            task.setDoRun(false);
            task.serviceSocket(null,null);
            getExecutor().execute(task);
            break; //regular shutdown
        }
        if ( socket == null ) continue;
        socket.setReceiveBufferSize(getRxBufSize());
        socket.setSendBufferSize(getTxBufSize());
        socket.setTcpNoDelay(getTcpNoDelay());
        socket.setKeepAlive(getSoKeepAlive());
        socket.setOOBInline(getOoBInline());
        socket.setReuseAddress(getSoReuseAddress());
        socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
        socket.setSoTimeout(getTimeout());
        ObjectReader reader = new ObjectReader(socket);
        task.serviceSocket(socket,reader);
        getExecutor().execute(task);
    }//while
}
 
Example 12
Source File: RapidoidWorker.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void configureSocket(SocketChannel socketChannel) throws IOException {
	socketChannel.configureBlocking(false);

	Socket socket = socketChannel.socket();
	socket.setTcpNoDelay(noDelay);
	socket.setReceiveBufferSize(bufSize);
	socket.setSendBufferSize(bufSize);
	socket.setReuseAddress(true);
}
 
Example 13
Source File: RedisConnection.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
void connect(String host, int timeoutInMs) throws IOException {
    socket = new Socket();
    socket.setReuseAddress(true);
    socket.setKeepAlive(true);
    socket.setTcpNoDelay(true); // Socket buffer whether closed, to ensure timely delivery of data
    socket.setSoLinger(true, 0); // Control calls close () method, the underlying socket is closed immediately
    socket.connect(new InetSocketAddress(host, DEFAULT_PORT), timeoutInMs);
    socket.setSoTimeout(timeoutInMs);
    outputStream = new RedisOutputStream(socket.getOutputStream(), 8192);
    inputStream = new RedisInputStream(socket.getInputStream());
}
 
Example 14
Source File: BioReceiver.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public void listen() throws Exception {
    if (doListen()) {
        log.warn("ServerSocket already started");
        return;
    }
    setListen(true);

    while ( doListen() ) {
        Socket socket = null;
        if ( getTaskPool().available() < 1 ) {
            if ( log.isWarnEnabled() )
                log.warn("All BIO server replication threads are busy, unable to handle more requests until a thread is freed up.");
        }
        BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask();
        if ( task == null ) continue; //should never happen
        try {
            socket = serverSocket.accept();
        }catch ( Exception x ) {
            if ( doListen() ) throw x;
        }
        if ( !doListen() ) {
            task.setDoRun(false);
            task.serviceSocket(null,null);
            getExecutor().execute(task);
            break; //regular shutdown
        }
        if ( socket == null ) continue;
        socket.setReceiveBufferSize(getRxBufSize());
        socket.setSendBufferSize(getTxBufSize());
        socket.setTcpNoDelay(getTcpNoDelay());
        socket.setKeepAlive(getSoKeepAlive());
        socket.setOOBInline(getOoBInline());
        socket.setReuseAddress(getSoReuseAddress());
        socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
        socket.setSoTimeout(getTimeout());
        ObjectReader reader = new ObjectReader(socket);
        task.serviceSocket(socket,reader);
        getExecutor().execute(task);
    }//while
}
 
Example 15
Source File: NetworkTransport.java    From firmata4j with MIT License 5 votes vote down vote up
@Override
public void start() throws IOException {
    socket = new Socket(ip, port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(1500);
    socket.setSoLinger(true, 1500);
    socket.setSoTimeout(1500);
    out = new DataOutputStream(socket.getOutputStream());
    in = new DataInputStream(socket.getInputStream());
    readerThread = new Thread(new Reader(), "firmata-network-transport");
    readerThread.start();
}
 
Example 16
Source File: ProxyHandler.java    From AndServer with Apache License 2.0 5 votes vote down vote up
private Socket createSocket(HttpHost host) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(60 * 1000);
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReceiveBufferSize(BUFFER);
    socket.setSendBufferSize(BUFFER);
    socket.setSoLinger(true, 0);

    String scheme = host.getSchemeName();
    String hostName = host.getHostName();
    int port = host.getPort();

    InetSocketAddress address = resolveAddress(scheme, hostName, port);
    socket.connect(address, 10 * 1000);

    if ("https".equalsIgnoreCase(scheme)) {
        SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(socket, hostName, port, true);
        try {
            sslSocket.startHandshake();
            final SSLSession session = sslSocket.getSession();
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available.");
            }
        } catch (final IOException ex) {
            IOUtils.closeQuietly(sslSocket);
            throw ex;
        }
        return sslSocket;
    }
    return socket;
}
 
Example 17
Source File: BioSocketChannelPool.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public static BioSocketChannel open(SocketAddress address) throws Exception {
    Socket socket = new Socket();
    socket.setSoTimeout(BioSocketChannel.SO_TIMEOUT);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReuseAddress(true);
    socket.connect(address, BioSocketChannel.DEFAULT_CONNECT_TIMEOUT);
    return new BioSocketChannel(socket);
}
 
Example 18
Source File: GameClient.java    From texaspoker with GNU General Public License v2.0 5 votes vote down vote up
public GameClient(String serverIp, int serverPort, String clientIp, 
        int clientPort, String playerID, boolean needNotify) {
    boolean flag = false;
    while (!flag) {
        try {
            socket = new Socket(); //此时Socket对象未绑定到本地端口,并且未连接远程服务器
            socket.setReuseAddress(true);

            SocketAddress localAddr = new InetSocketAddress(clientIp, clientPort);
            SocketAddress remoteAddr = new InetSocketAddress(serverIp, serverPort);

            socket.bind(localAddr); //与本地端口绑定
            
            socket.connect(remoteAddr, 200);
            flag = true;
            System.out.println("success!");
            input = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream(), true);
            
        } catch (Exception e) {
            System.out.println("connect failed,try again!");
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }
    
    this.playerID = playerID;
    if (needNotify) {
        this.needNotify = "need_notify ";
    }
    else {
        this.needNotify = "";
    }
}
 
Example 19
Source File: ProxyTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void smallLatency() throws Exception {
  server = new Server();
  int serverPort = server.init();
  executor.execute(server);

  int latency = (int) TimeUnit.MILLISECONDS.toNanos(50);
  proxy = new TrafficControlProxy(serverPort, 1024 * 1024, latency, TimeUnit.NANOSECONDS);
  startProxy(proxy).get();
  client = new Socket("localhost", proxy.getPort());
  client.setReuseAddress(true);
  DataOutputStream clientOut = new DataOutputStream(client.getOutputStream());
  DataInputStream clientIn = new DataInputStream(client.getInputStream());
  byte[] message = new byte[1];

  // warmup
  for (int i = 0; i < 5; i++) {
    clientOut.write(message, 0, 1);
  }
  clientIn.readFully(new byte[5]);

  // test
  long start = System.nanoTime();
  clientOut.write(message, 0, 1);
  clientIn.read(message);
  long stop = System.nanoTime();

  long rtt = (stop - start);
  assertEquals(latency, rtt, latency);
}
 
Example 20
Source File: ClientGlobal.java    From fastdfs-client-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * construct Socket object
 *
 * @param addr InetSocketAddress object, including ip address and port
 * @return connected Socket object
 */
public static Socket getSocket(InetSocketAddress addr) throws IOException {
  Socket sock = new Socket();
  sock.setReuseAddress(true);
  sock.setSoTimeout(ClientGlobal.g_network_timeout);
  sock.connect(addr, ClientGlobal.g_connect_timeout);
  return sock;
}