Example usage for java.net Socket setSendBufferSize

List of usage examples for java.net Socket setSendBufferSize

Introduction

In this page you can find the example usage for java.net Socket setSendBufferSize.

Prototype

public synchronized void setSendBufferSize(int size) throws SocketException 

Source Link

Document

Sets the SocketOptions#SO_SNDBUF SO_SNDBUF option to the specified value for this Socket .

Usage

From source file:org.globus.ftp.dc.GridFTPPassiveConnectTask.java

protected SocketBox openSocket() throws Exception {

    logger.debug("server.accept()");

    Socket newSocket = myServer.accept();

    // set TCP buffer size
    if (gSession.TCPBufferSize != Session.SERVER_DEFAULT) {
        logger.debug("setting socket's TCP buffer size to " + gSession.TCPBufferSize);
        newSocket.setReceiveBufferSize(gSession.TCPBufferSize);
        newSocket.setSendBufferSize(gSession.TCPBufferSize);
    }//w w  w  .jav a  2  s.c o  m

    logger.debug("server.accept() returned");

    if (!gSession.dataChannelAuthentication.equals(DataChannelAuthentication.NONE)) {
        logger.debug("authenticating");
        newSocket = GridFTPServerFacade.authenticate(newSocket, false, // this is NOT client socket
                gSession.credential, gSession.dataChannelProtection, gSession.dataChannelAuthentication);
    } else {
        // do not authenticate
        logger.debug("not authenticating");
    }

    // mark the socket as busy and store in the global socket pool

    ManagedSocketBox sBox = new ManagedSocketBox();
    sBox.setSocket(newSocket);
    sBox.setStatus(ManagedSocketBox.BUSY);

    if (session.transferMode != GridFTPSession.MODE_EBLOCK) {

        // synchronize to prevent race condidion against
        // the section in GridFTPServerFacade.setTCPBufferSize
        synchronized (sBox) {
            sBox.setReusable(false);
        }
    }

    SocketPool socketPool = ((EBlockParallelTransferContext) context).getSocketPool();
    logger.debug("adding new socket to the pool");
    socketPool.add(sBox);
    logger.debug("available cached sockets: " + socketPool.countFree() + "; busy: " + socketPool.countBusy());

    return sBox;

}

From source file:org.globus.ftp.extended.GridFTPServerFacade.java

/**
   This method needs to be called BEFORE the local socket(s) get created.
   In other words, before setActive(), setPassive(), get(), put(), etc.
**//*  ww  w  . j av  a  2 s  .c om*/
public void setTCPBufferSize(final int size) throws ClientException {
    logger.debug("Changing local TCP buffer setting to " + size);

    gSession.TCPBufferSize = size;

    SocketOperator op = new SocketOperator() {
        public void operate(SocketBox s) throws Exception {

            // synchronize to prevent race condition against
            // the socket initialization code that also sets
            // TCP buffer (GridFTPActiveConnectTask)
            synchronized (s) {
                logger.debug("Changing local socket's TCP buffer to " + size);
                Socket mySocket = s.getSocket();
                if (mySocket != null) {
                    mySocket.setReceiveBufferSize(size);
                    mySocket.setSendBufferSize(size);
                } else {
                    logger.debug("the socket is null. probably being initialized");
                }
            }
        }
    };
    try {
        socketPool.applyToAll(op);
    } catch (Exception e) {
        ClientException ce = new ClientException(ClientException.SOCKET_OP_FAILED);
        ce.setRootCause(e);
        throw ce;
    }
}

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  ww  .  j  a v a 2  s . co  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  a  v a2s.  com*/
 * @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   w  w  w.  jav  a  2 s .  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.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Sets socket attributes on the socket.
 * @param socket The socket.//w  w  w . j  a  v  a2 s.  com
 * @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);
}

From source file:voldemort.store.socket.SocketPoolableObjectFactory.java

/**
 * Create a socket for the given host/port
 *///from   w ww.j a  v  a2s.  c om
public Object makeObject(Object key) throws Exception {
    SocketDestination dest = (SocketDestination) key;
    Socket socket = new Socket();
    socket.setReceiveBufferSize(this.socketBufferSize);
    socket.setSendBufferSize(this.socketBufferSize);
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(soTimeoutMs);
    socket.connect(new InetSocketAddress(dest.getHost(), dest.getPort()));

    recordSocketCreation(dest, socket);

    return new SocketAndStreams(socket);
}