Java Code Examples for java.net.Socket#setReuseAddress()
The following examples show how to use
java.net.Socket#setReuseAddress() .
These examples are extracted from open source projects.
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 Project: brooklyn-server File: Networking.java License: Apache License 2.0 | 6 votes |
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 Project: grpc-nebula-java File: UtilsTest.java License: Apache License 2.0 | 6 votes |
@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 Project: netty4.0.27Learn File: EpollReuseAddrTest.java License: Apache License 2.0 | 6 votes |
@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 4
Source Project: netty-4.1.22 File: EpollReuseAddrTest.java License: Apache License 2.0 | 6 votes |
@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 5
Source Project: Java-OCA-OCPP File: BaseWssSocketBuilder.java License: MIT License | 6 votes |
@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 6
Source Project: mars-sim File: MultiplayerClient.java License: GNU General Public License v3.0 | 6 votes |
/** * 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 7
Source Project: syslog4j-graylog2 File: TCPNetSyslogWriter.java License: GNU Lesser General Public License v2.1 | 6 votes |
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 8
Source Project: openhab1-addons File: TCPMasterConnection.java License: Eclipse Public License 2.0 | 6 votes |
/** * 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 9
Source Project: Tomcat7.0.67 File: SocketProperties.java License: Apache License 2.0 | 6 votes |
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 10
Source Project: Tomcat8-Source-Read File: BioReceiver.java License: MIT License | 5 votes |
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 11
Source Project: fastdfs-client-java File: ClientGlobal.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 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; }
Example 12
Source Project: grpc-nebula-java File: ProxyTest.java License: Apache License 2.0 | 5 votes |
@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 13
Source Project: texaspoker File: GameClient.java License: GNU General Public License v2.0 | 5 votes |
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 14
Source Project: canal-1.1.3 File: BioSocketChannelPool.java License: Apache License 2.0 | 5 votes |
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 15
Source Project: AndServer File: ProxyHandler.java License: Apache License 2.0 | 5 votes |
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 16
Source Project: firmata4j File: NetworkTransport.java License: MIT License | 5 votes |
@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 17
Source Project: Tomcat7.0.67 File: BioReceiver.java License: Apache License 2.0 | 5 votes |
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 18
Source Project: core-ng-project File: RedisConnection.java License: Apache License 2.0 | 5 votes |
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 19
Source Project: rapidoid File: RapidoidWorker.java License: Apache License 2.0 | 5 votes |
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 20
Source Project: tomcatsrc File: BioReceiver.java License: Apache License 2.0 | 5 votes |
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 }