List of usage examples for java.net Socket setSoLinger
public void setSoLinger(boolean on, int linger) throws SocketException
From source file:org.apache.tomcat.util.net.PoolTcpEndpoint.java
protected void closeServerSocket() { Socket s = null; try {/*from ww w.jav a 2 s. c om*/ // Need to create a connection to unlock the accept(); if (inet == null) { s = new Socket("127.0.0.1", port); } else { s = new Socket(inet, port); // setting soLinger to a small value will help shutdown the // connection quicker s.setSoLinger(true, 0); } } catch (Exception e) { log.error("Caught exception trying to unlock accept on " + port + " " + e.toString()); } finally { if (s != null) { try { s.close(); } catch (Exception e) { // Ignore } } } try { if (serverSocket != null) serverSocket.close(); } catch (Exception e) { log.error("Caught exception trying to close socket.", e); } serverSocket = null; }
From source file:org.apache.tomcat.util.net.PoolTcpEndpoint.java
void setSocketOptions(Socket socket) throws SocketException { if (linger >= 0) socket.setSoLinger(true, linger); if (tcpNoDelay) socket.setTcpNoDelay(tcpNoDelay); if (socketTimeout > 0) socket.setSoTimeout(socketTimeout); }
From source file:org.codehaus.mojo.cassandra.Utils.java
/** * Stops the Cassandra service.//from w w w. j av a2 s . com * * @param rpcAddress The rpcAddress to connect to in order to see if Cassandra has stopped. * @param rpcPort The rpcPort to connect on to check if Cassandra has stopped. * @param stopPort The port to stop on. * @param stopKey The key to stop with, * @param log The log to write to. */ static void stopCassandraServer(String rpcAddress, int rpcPort, String stopAddress, int stopPort, String stopKey, Log log) { try { Socket s = new Socket(InetAddress.getByName(stopAddress), stopPort); s.setSoLinger(false, 0); OutputStream out = s.getOutputStream(); out.write((stopKey + "\r\nstop\r\n").getBytes()); out.flush(); s.close(); } catch (ConnectException e) { log.info("Cassandra not running!"); return; } catch (Exception e) { log.error(e); return; } log.info("Waiting for Cassandra to stop..."); long maxWaiting = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30); boolean stopped = false; while (!stopped && System.currentTimeMillis() < maxWaiting) { TTransport tr = new TFramedTransport(new TSocket(rpcAddress, rpcPort)); try { TProtocol proto = new TBinaryProtocol(tr); Cassandra.Client client = new Cassandra.Client(proto); try { tr.open(); } catch (TTransportException e) { if (e.getCause() instanceof ConnectException) { stopped = true; continue; } log.debug(e.getLocalizedMessage(), e); try { Thread.sleep(500); } catch (InterruptedException e1) { // ignore } } } finally { if (tr.isOpen()) { tr.close(); } } } if (stopped) { log.info("Cassandra has stopped."); } else { log.warn("Gave up waiting for Cassandra to stop."); } }
From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java
@Override public Socket createConnection() throws Exception { Socket socket = new Socket(); try {/*from w ww.ja v a 2s.co m*/ if (sendBufferSize > 0) socket.setSendBufferSize(sendBufferSize); if (receiveBufferSize > 0) socket.setReceiveBufferSize(receiveBufferSize); if (soTimeout > 0) socket.setSoTimeout(soTimeout); if (linger > 0) socket.setSoLinger(true, linger); if (keepAlive) socket.setKeepAlive(keepAlive); if (tcpNoDelay) socket.setTcpNoDelay(tcpNoDelay); if (performance != null) socket.setPerformancePreferences(Integer.parseInt(performance[0]), Integer.parseInt(performance[1]), Integer.parseInt(performance[2])); socket.connect(socketAddress, connectionTimeout); } catch (Exception se) { socket.close(); throw se; } return socket; }
From source file:org.mule.transport.tcp.issues.LingerExperimentMule2067TestCase.java
protected void openCloseClientServer(int numberOfConnections, int port, int clientLinger, int serverLinger) throws IOException { Server server = new Server(port, serverLinger); try {//from w w w .j av a 2 s .c o m new Thread(server).start(); for (int i = 0; i < numberOfConnections; i++) { logger.debug("opening socket " + i); Socket client = new Socket("localhost", port); if (NO_LINGER != clientLinger) { client.setSoLinger(true, clientLinger); } client.close(); } } finally { server.close(); } }
From source file:org.mule.transport.tcp.TcpConnector.java
public void configureSocket(boolean client, Socket socket) throws SocketException { // There is some overhead in setting socket timeout and buffer size, so we're // careful here only to set if needed if (newValue(getReceiveBufferSize(), socket.getReceiveBufferSize())) { socket.setReceiveBufferSize(getReceiveBufferSize()); }/*w w w.jav a2 s .c o m*/ if (newValue(getSendBufferSize(), socket.getSendBufferSize())) { socket.setSendBufferSize(getSendBufferSize()); } if (client) { if (newValue(getClientSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getClientSoTimeout()); } } else { if (newValue(getServerSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getServerSoTimeout()); } } if (newValue(getSocketSoLinger(), socket.getSoLinger())) { socket.setSoLinger(true, getSocketSoLinger()); } try { socket.setTcpNoDelay(isSendTcpNoDelay()); } catch (SocketException e) { // MULE-2800 - Bug in Solaris } socket.setKeepAlive(isKeepAlive()); }
From source file:org.quickserver.net.server.QuickServer.java
/** * Starts server in blocking mode./*w w w . j ava2 s .c o m*/ * @since 1.4.5 */ private void runBlocking(TheClient theClient) throws Exception { Socket client = null; ClientHandler _chPolled = null; int linger = getBasicConfig().getAdvancedSettings().getSocketLinger(); int socketTrafficClass = 0; if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { socketTrafficClass = Integer .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass()); } //long stime = System.currentTimeMillis(); //long etime = System.currentTimeMillis(); while (true) { //etime = System.currentTimeMillis(); //System.out.println("Time Taken: "+(etime-stime)); client = server.accept(); //stime = System.currentTimeMillis(); if (linger < 0) { client.setSoLinger(false, 0); } else { client.setSoLinger(true, linger); } client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay()); if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { client.setTrafficClass(socketTrafficClass);//low delay=10 } //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize()); if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) { client.setSendBufferSize(getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize()); //logger.fine("SendBufferSize: "+client.getSendBufferSize()); } if (stopServer) { //Client connected when server was about to be shutdown. try { client.close(); } catch (Exception e) { } break; } if (checkAccessConstraint(client) == false) { continue; } //Check if max connection has reached if (getSkipValidation() != true && maxConnection != -1 && getClientHandlerPool().getNumActive() >= maxConnection) { theClient.setClientEvent(ClientEvent.MAX_CON_BLOCKING); } else { theClient.setClientEvent(ClientEvent.RUN_BLOCKING); } theClient.setTrusted(getSkipValidation()); theClient.setSocket(client); theClient.setSocketChannel(client.getChannel()); //mostly null if (clientDataClass != null) { if (getClientDataPool() == null) { clientData = (ClientData) clientDataClass.newInstance(); } else { clientData = (ClientData) getClientDataPool().borrowObject(); } theClient.setClientData(clientData); } try { _chPolled = (ClientHandler) getClientHandlerPool().borrowObject(); _chPolled.handleClient(theClient); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow ClientHandler from pool. Error: " + nsee); logger.warning("Closing Socket [" + client + "] since no ClientHandler available."); client.close(); } if (_chPolled != null) { try { getClientPool().addClient(_chPolled, true); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow Thread from pool. Error: " + nsee); //logger.warning("Closing Socket ["+client+"] since no Thread available."); //client.close(); //returnClientHandlerToPool(_chPolled); } _chPolled = null; } client = null; //reset it back setSkipValidation(false); } //end of loop }
From source file:org.quickserver.net.server.QuickServer.java
/** * Starts server in non-blocking mode./*from ww w.j a v a 2s .co m*/ * @since 1.4.5 */ private void runNonBlocking(TheClient theClient) throws Exception { int selectCount = 0; Iterator iterator = null; SelectionKey key = null; ServerSocketChannel serverChannel = null; SocketChannel socketChannel = null; Socket client = null; ClientHandler _chPolled = null; boolean stopServerProcessed = false; int linger = getBasicConfig().getAdvancedSettings().getSocketLinger(); registerChannelRequestMap = new HashMap(); int socketTrafficClass = 0; if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { socketTrafficClass = Integer .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass()); } while (true) { selectCount = selector.select(500); //selectCount = selector.select();//for testing //check for any pending registerChannel req. synchronized (registerChannelRequestMap) { if (registerChannelRequestMap.size() > 0) { RegisterChannelRequest req = null; Object hashkey = null; iterator = registerChannelRequestMap.keySet().iterator(); while (iterator.hasNext()) { hashkey = iterator.next(); req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey); req.register(getSelector()); } iterator = null; registerChannelRequestMap.clear(); } //if } //sync if (stopServer == true && stopServerProcessed == false) { logger.warning("Closing " + getName()); serverSocketChannel.close(); stopServerProcessed = true; server = null; serverSocketChannel = null; setServiceState(Service.STOPPED); logger.warning("Closed " + getName()); processServerHooks(ServerHook.POST_SHUTDOWN); } if (stopServer == false && stopServerProcessed == true) { logger.finest("Server must have re-started.. will break"); break; } if (selectCount == 0 && stopServerProcessed == true) { java.util.Set keyset = selector.keys(); if (keyset.isEmpty() == true && getClientCount() <= 0) { break; } else { continue; } } else if (selectCount == 0) { continue; } iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); if (key.isValid() == false) { iterator.remove(); continue; } if (key.isAcceptable() && stopServer == false) { logger.finest("Key is Acceptable"); serverChannel = (ServerSocketChannel) key.channel(); socketChannel = serverChannel.accept(); if (socketChannel == null) { iterator.remove(); continue; } client = socketChannel.socket(); if (linger < 0) { client.setSoLinger(false, 0); } else { client.setSoLinger(true, linger); } client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay()); if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { client.setTrafficClass(socketTrafficClass);//low delay=10 } //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize()); if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) { client.setSendBufferSize( getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize()); //logger.fine("SendBufferSize: "+client.getSendBufferSize()); } if (checkAccessConstraint(client) == false) { iterator.remove(); continue; } socketChannel.configureBlocking(false); theClient.setTrusted(getSkipValidation()); theClient.setSocket(socketChannel.socket()); theClient.setSocketChannel(socketChannel); if (clientDataClass != null) { if (getClientDataPool() == null) { clientData = (ClientData) clientDataClass.newInstance(); } else { //borrow a object from pool clientData = (ClientData) getClientDataPool().borrowObject(); } theClient.setClientData(clientData); } //Check if max connection has reached if (getSkipValidation() != true && maxConnection != -1 && getClientHandlerPool().getNumActive() >= maxConnection) { theClient.setClientEvent(ClientEvent.MAX_CON); } else { theClient.setClientEvent(ClientEvent.ACCEPT); } try { _chPolled = (ClientHandler) getClientHandlerPool().borrowObject(); logger.finest("Asking " + _chPolled.getName() + " to handle."); _chPolled.handleClient(theClient); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee); logger.warning("Closing SocketChannel [" + serverChannel.socket() + "] since no ClientHandler available."); socketChannel.close(); } if (_chPolled != null) { try { getClientPool().addClient(_chPolled, true); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow Thread from pool. Error: " + nsee); //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available."); //socketChannel.close(); //returnClientHandlerToPool(_chPolled); } _chPolled = null; } socketChannel = null; client = null; setSkipValidation(false);//reset it back } else if (key.isValid() && key.isReadable()) { boolean addedEvent = false; ClientHandler _ch = null; try { _ch = (ClientHandler) key.attachment(); logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName()); key.interestOps(key.interestOps() & (~SelectionKey.OP_READ)); _ch.addEvent(ClientEvent.READ); addedEvent = true; //_ch.setSelectionKey(key); getClientPool().addClient(_ch); } catch (CancelledKeyException cke) { logger.fine("Ignored Error - Key was Cancelled: " + cke); } catch (java.util.NoSuchElementException nsee) { logger.finest("NoSuchElementException: " + nsee); if (addedEvent) _ch.removeEvent(ClientEvent.READ); continue;//no need to remove the key } _ch = null; } else if (key.isValid() && key.isWritable()) { if (getClientPool().shouldNioWriteHappen() == false) { continue; //no need to remove the key } boolean addedEvent = false; ClientHandler _ch = null; try { _ch = (ClientHandler) key.attachment(); logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName()); //remove OP_WRITE from interest set key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); _ch.addEvent(ClientEvent.WRITE); addedEvent = true; //_ch.setSelectionKey(key); getClientPool().addClient(_ch); } catch (CancelledKeyException cke) { logger.fine("Ignored Error - Key was Cancelled: " + cke); } catch (java.util.NoSuchElementException nsee) { logger.finest("NoSuchElementException: " + nsee); if (addedEvent) _ch.removeEvent(ClientEvent.WRITE); continue;//no need to remove the key } _ch = null; } else if (stopServer == true && key.isAcceptable()) { //we will not accept this key setSkipValidation(false);//reset it back } else { logger.warning("Unknown key got in SelectionKey: " + key); } iterator.remove(); //Remove key Thread.yield(); } //end of iterator iterator = null; } //end of loop }
From source file:org.rhq.plugins.platform.content.yum.YumServer.java
/** * Listen for and process requests.//from w w w .j a va 2 s . c o m */ private void listen() { try { Socket client = socket.accept(); client.setTcpNoDelay(true); client.setSoLinger(false, 0); Request request = new Request(this, client); request.process(); } catch (SocketTimeoutException te) { // expected } catch (Exception e) { log.warn("listen failed", e); run = false; } }
From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java
/** * Sets socket attributes on the socket. * @param socket The socket.//w w w. ja v a2s .c o m * @throws SocketException */ protected void setSocketAttributes(Socket socket) throws SocketException { if (this.soTimeout >= 0) { socket.setSoTimeout(this.soTimeout); } if (this.soSendBufferSize > 0) { socket.setSendBufferSize(this.soSendBufferSize); } if (this.soReceiveBufferSize > 0) { socket.setReceiveBufferSize(this.soReceiveBufferSize); } socket.setTcpNoDelay(this.soTcpNoDelay); if (this.soLinger >= 0) { socket.setSoLinger(true, this.soLinger); } if (this.soTrafficClass >= 0) { socket.setTrafficClass(this.soTrafficClass); } socket.setKeepAlive(this.soKeepAlive); }