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

The following are Jave code examples for showing how to use setReuseAddress() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: SocketProperties.java   Source Code and License Vote up 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 2
Project: crush   File: DRPMessenger.java   Source Code and License Vote up 6 votes
private synchronized void send(Message message) throws IOException {
	if(message == null) return;
			
	Socket socket = new Socket();
	socket.setReuseAddress(true);
	socket.setPerformancePreferences(2, 1, 0); // connection, latency, bandwidth
	socket.setTcpNoDelay(true);
	socket.setTrafficClass(0x10);	// low delay
	socket.setSoTimeout(timeoutMillis);
	socket.connect(address);
		
	@SuppressWarnings("resource")
       OutputStream out = socket.getOutputStream();
	
	// TODO additional check. Is it needed?
	if(out == null) throw new IOException("Socket has no output stream.");
	
	String text = message.toString();
	out.write(text.getBytes());
	
	if(CRUSH.debug) CRUSH.debug(this, "DRP> " + text);
	
	out.flush();
	socket.close();
}
 
Example 3
Project: lazycat   File: SocketProperties.java   Source Code and License Vote up 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 4
Project: TK_1701   File: ClientSocketHandler.java   Source Code and License Vote up 5 votes
@Override
public void run() {
    Log.d(TAG,"run");
    Socket socket = new Socket();
    try {
        /*
        note: setReuseAddress
        When closing a TCP connection, the connection may stay in a time-out state (usually
        referred to as TIME_WAIT state or 2 MSL wait state) for a period of time after the
        close of the connection. For applications that use the well-known socket address or port,
        sockets associated with a socket address or port may be unable to bind to the required
        SocketAddress if it is in the timeout state.
         */
        InetSocketAddress addr = new InetSocketAddress(mAddress.getHostAddress(),WiFiDirectCommunicator.PORT);
        socket.bind(null);
        socket.setReuseAddress(true);
        socket.connect(addr,WiFiDirectCommunicator.TIMEOUT);
        Log.d(TAG, "Launching the I/O handler");
        manager = new CommManager(socket, handler);
        new Thread(manager).start();
    } catch (IOException e) {
        e.printStackTrace();
        try {
            socket.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return;
    }
}
 
Example 5
Project: socket-client-server   File: TCPClient.java   Source Code and License Vote up 5 votes
private void connectActually(){
    try {
        mSocket = new Socket(this.ip,this.port);
        mSocket.setTcpNoDelay(true);
        mSocket.setReuseAddress(true);
        mDataInputStream = new DataInputStream(mSocket.getInputStream());
        mDataOutputStream = new DataOutputStream(mSocket.getOutputStream());
    } catch (IOException e) {
        if(mTCPResultListener !=null){
            mTCPResultListener.onConnectFailed(e.getMessage());
        }

    }
}
 
Example 6
Project: WifiChatSharing   File: PrivateChatActivity.java   Source Code and License Vote up 5 votes
public void run() {
    updateUIToast("creatting socket");

    try {
        clientSocket = new Socket(clientIpAddress, SocketServerPORT + 1);
        clientSocket.setReuseAddress(true);
        //clientSocket.bind(new InetSocketAddress(SocketServerPORT + 1));

        updateUI(getIpAddress(), clientSocket.toString());

        outp = new PrintWriter(clientSocket.getOutputStream(), true);
        inp = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        System.out.println(clientSocket.getInetAddress().getHostAddress() + " is ther server");
        updateUIToast(clientSocket.getInetAddress().getHostAddress() + " is ther server");
    } catch (IOException e) {
        e.printStackTrace();
        updateUIToast(e.toString());

    }

    if (clientSocket != null) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                connectClientButton.setVisibility(View.GONE);
            }
        });
    }


}
 
Example 7
Project: iBase4J-Common   File: TrackerGroup.java   Source Code and License Vote up 5 votes
/**
 * return connected tracker server
 *
 * @return connected tracker server, null for fail
 * @throws IOException if an error occurred
 */
public TrackerServer getConnection(int serverIndex) throws IOException {
    Socket sock = new Socket();
    sock.setReuseAddress(true);
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(this.tracker_servers[serverIndex], ClientGlobal.g_connect_timeout);
    return new TrackerServer(sock, this.tracker_servers[serverIndex]);
}
 
Example 8
Project: elasticsearch_my   File: MockTcpTransport.java   Source Code and License Vote up 5 votes
private void configureSocket(Socket socket) throws SocketException {
    socket.setTcpNoDelay(TCP_NO_DELAY.get(settings));
    ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.getBytes() > 0) {
        socket.setSendBufferSize(tcpSendBufferSize.bytesAsInt());
    }
    ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.getBytes() > 0) {
        socket.setReceiveBufferSize(tcpReceiveBufferSize.bytesAsInt());
    }
    socket.setReuseAddress(TCP_REUSE_ADDRESS.get(settings));
}
 
Example 9
Project: JAVA-   File: ServerInfo.java   Source Code and License Vote up 5 votes
/**
* connect to server
* @return connected Socket object
*/
	public Socket connect() throws IOException
	{
		Socket sock = new Socket();
		sock.setReuseAddress(true);
		sock.setSoTimeout(ClientGlobal.g_network_timeout);
		sock.connect(new InetSocketAddress(this.ip_addr, this.port), ClientGlobal.g_connect_timeout);
		return sock;
	}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: BioReceiver.java   Source Code and License Vote up 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 11
Project: JAVA-   File: TrackerGroup.java   Source Code and License Vote up 5 votes
/**
 * return connected tracker server
 *
 * @return connected tracker server, null for fail
 */
public TrackerServer getConnection(int serverIndex) throws IOException {
    Socket sock = new Socket();
    sock.setReuseAddress(true);
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(this.tracker_servers[serverIndex], ClientGlobal.g_connect_timeout);
    return new TrackerServer(sock, this.tracker_servers[serverIndex]);
}
 
Example 12
Project: tomcat7   File: BioSender.java   Source Code and License Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled
 * is socket open return directly
 */
protected void openSocket() throws IOException {
   if(isConnected()) return ;
   try {
       socket = new Socket();
       InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
       socket.connect(sockaddr,(int)getTimeout());
       socket.setSendBufferSize(getTxBufSize());
       socket.setReceiveBufferSize(getRxBufSize());
       socket.setSoTimeout( (int) getTimeout());
       socket.setTcpNoDelay(getTcpNoDelay());
       socket.setKeepAlive(getSoKeepAlive());
       socket.setReuseAddress(getSoReuseAddress());
       socket.setOOBInline(getOoBInline());
       socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
       socket.setTrafficClass(getSoTrafficClass());
       setConnected(true);
       soOut = socket.getOutputStream();
       soIn  = socket.getInputStream();
       setRequestCount(0);
       setConnectTime(System.currentTimeMillis());
       if (log.isDebugEnabled())
           log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)));
  } catch (IOException ex1) {
      SenderState.getSenderState(getDestination()).setSuspect();
      if (log.isDebugEnabled())
          log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
      throw (ex1);
    }
    
 }
 
Example 13
Project: AirPlayAuth   File: AirPlayAuth.java   Source Code and License Vote up 5 votes
private Socket connect() throws IOException {
    Socket socket = new Socket();
    socket.setReuseAddress(true);
    socket.setSoTimeout(SOCKET_TIMEOUT);
    socket.connect(address, SOCKET_TIMEOUT);
    return socket;
}
 
Example 14
Project: mumu   File: ServerInfo.java   Source Code and License Vote up 5 votes
/**
* connect to server
* @return connected Socket object
*/
	public Socket connect() throws IOException
	{
		Socket sock = new Socket();
		sock.setReuseAddress(true);
		sock.setSoTimeout(ClientGlobal.g_network_timeout);
		sock.connect(new InetSocketAddress(this.ip_addr, this.port), ClientGlobal.g_connect_timeout);
		return sock;
	}
 
Example 15
Project: mumu   File: TrackerGroup.java   Source Code and License Vote up 5 votes
/**
* return connected tracker server
* @return connected tracker server, null for fail
*/
	public TrackerServer getConnection(int serverIndex) throws IOException
	{
		Socket sock = new Socket();
		sock.setReuseAddress(true);
		sock.setSoTimeout(ClientGlobal.g_network_timeout);
		sock.connect(this.tracker_servers[serverIndex], ClientGlobal.g_connect_timeout);
		return new TrackerServer(sock, this.tracker_servers[serverIndex]);
	}
 
Example 16
Project: lams   File: PlainSocketFactory.java   Source Code and License Vote up 5 votes
/**
 * @since 4.1
 */
public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params) throws IOException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket;
    if (sock == null) {
        sock = createSocket();
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}
 
Example 17
Project: FirefoxData-android   File: PlainSocketFactory.java   Source Code and License Vote up 5 votes
/**
 * @since 4.1
 */
public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params) throws IOException, ConnectTimeoutException {
    Args.notNull(remoteAddress, "Remote address");
    Args.notNull(params, "HTTP parameters");
    Socket sock = socket;
    if (sock == null) {
        sock = createSocket();
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    final int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (final SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}
 
Example 18
Project: iBase4J   File: TrackerGroup.java   Source Code and License Vote up 5 votes
/**
 * return connected tracker server
 *
 * @return connected tracker server, null for fail
 */
public TrackerServer getConnection(int serverIndex) throws IOException {
    Socket sock = new Socket();
    sock.setReuseAddress(true);
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(this.tracker_servers[serverIndex], ClientGlobal.g_connect_timeout);
    return new TrackerServer(sock, this.tracker_servers[serverIndex]);
}
 
Example 19
Project: lazycat   File: BioSender.java   Source Code and License Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled is socket
 * open return directly
 */
protected void openSocket() throws IOException {
	if (isConnected())
		return;
	try {
		socket = new Socket();
		InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
		socket.connect(sockaddr, (int) getTimeout());
		socket.setSendBufferSize(getTxBufSize());
		socket.setReceiveBufferSize(getRxBufSize());
		socket.setSoTimeout((int) getTimeout());
		socket.setTcpNoDelay(getTcpNoDelay());
		socket.setKeepAlive(getSoKeepAlive());
		socket.setReuseAddress(getSoReuseAddress());
		socket.setOOBInline(getOoBInline());
		socket.setSoLinger(getSoLingerOn(), getSoLingerTime());
		socket.setTrafficClass(getSoTrafficClass());
		setConnected(true);
		soOut = socket.getOutputStream();
		soIn = socket.getInputStream();
		setRequestCount(0);
		setConnectTime(System.currentTimeMillis());
		if (log.isDebugEnabled())
			log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(),
					Integer.valueOf(getPort()), Long.valueOf(0)));
	} catch (IOException ex1) {
		SenderState.getSenderState(getDestination()).setSuspect();
		if (log.isDebugEnabled())
			log.debug(sm.getString("IDataSender.openSocket.failure", getAddress().getHostAddress(),
					Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
		throw (ex1);
	}

}
 
Example 20
Project: lazycat   File: BioReceiver.java   Source Code and License Vote up 4 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
}