Example usage for java.net Socket setTcpNoDelay

List of usage examples for java.net Socket setTcpNoDelay

Introduction

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

Prototype

public void setTcpNoDelay(boolean on) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#TCP_NODELAY TCP_NODELAY (disable/enable Nagle's algorithm).

Usage

From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java

private void initSocket(Socket socket) throws SocketException {
    logger.debug("Initializing socket (" + connectorProperties.getName() + " \"Source\" on channel "
            + getChannelId() + ").");
    socket.setReceiveBufferSize(bufferSize);
    socket.setSendBufferSize(bufferSize);
    socket.setSoTimeout(timeout);//from  w  w w.j ava 2 s. c o  m
    socket.setKeepAlive(connectorProperties.isKeepConnectionOpen());
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
}

From source file:com.jcraft.weirdx.WeirdX.java

public void weirdx_start(Container container) throws ConnectException {
    if (xdmcpmode != null) {
        LOG.debug("XDMC Mode = " + xdmcpmode);
        if (xdmcpmode.equals("query")) {
            xdmcp = new XDMCP(xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("broadcast")) {
            xdmcp = new XDMCP(XDMCP.BroadcastQuery, xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("indirect")) {
            xdmcp = new XDMCP(XDMCP.IndirectQuery, xdmcpaddr, myAddress, displayNumber);
        }/*  w  ww .  jav  a 2s . c  o m*/
    }

    if (sxrexec != null && sxrexec.equals("yes")) {
        xrexec = new XRexec(myAddress, displayNumber);
    }

    weirdx_init(container);

    InputStream in;
    OutputStream out;

    InputOutput client = null;

    if (xdmcp != null) {
        Client.addListener((ClientListener) xdmcp);
        xdmcp.start();
    }

    if (jdxpc != null) {
        (new SpawnJDxpc(this)).start();
    }
    if (ssshrexec != null) {
        if (ssshrexec.equals("yes")) {
            (new SpawnSSHRexec(this)).start();
        }
    }

    byte[] byte_order = new byte[1];
    try {
        Socket socket = null;
        while (true && weirdx != null) {
            try {
                socket = displaysocket.accept();
            } catch (Exception e) {
                LOG.error(e);
                if (e instanceof NullPointerException) {
                    weirdx = null;
                    break;
                }
                continue;
            }

            if (!Acl.check(socket.getInetAddress())) {
                LOG.error("ACL warning: unauthorized access from " + socket.getInetAddress());
                try {
                    socket.close();
                } catch (Exception e) {
                }
                ;
                continue;
            }

            try {
                socket.setTcpNoDelay(true);
            } catch (Exception eeee) {
                //System.out.println(eeee+" tcpnodelay");
            }

            client = null;

            in = socket.getInputStream();
            out = socket.getOutputStream();

            try {
                in.read(byte_order, 0, 1);
            } catch (Exception e) {
                continue;
            }

            // 0x6c LSB
            // 0x42 MSB
            if (byte_order[0] == 0x6c) {
                client = new IOLSB();
            } else if (byte_order[0] == 0x42) {
                client = new IOMSB();
            } else {
                LOG.warn("protocol: error " + Integer.toHexString(byte_order[0]));
                continue;
            }

            client.setInputStream(in);
            client.setOutputStream(out);

            Client foo = new Client(client);
            if (foo.index != -1) {
                foo.start();
            } else {
                // System.err.println("running over clients table");
            }
        }
    } catch (IOException e) {
        LOG.error("IO Error: " + e.getLocalizedMessage());
    }
    // stop(); // ??
}

From source file:org.apache.jmeter.protocol.tcp.sampler.TCPSampler.java

private Socket getSocket(String socketKey) {
    Map<String, Object> cp = tp.get();
    Socket con = null;
    if (isReUseConnection()) {
        con = (Socket) cp.get(socketKey);
        if (con != null) {
            log.debug(this + " Reusing connection " + con); //$NON-NLS-1$
        }/* w w  w  .  ja  va  2 s  .  c  om*/
    }
    if (con == null) {
        // Not in cache, so create new one and cache it
        try {
            closeSocket(socketKey); // Bug 44910 - close previous socket (if any)
            SocketAddress sockaddr = new InetSocketAddress(getServer(), getPort());
            con = new Socket();
            if (getPropertyAsString(SO_LINGER, "").length() > 0) {
                con.setSoLinger(true, getSoLinger());
            }
            con.connect(sockaddr, getConnectTimeout());
            if (log.isDebugEnabled()) {
                log.debug("Created new connection " + con); //$NON-NLS-1$
            }
            cp.put(socketKey, con);
        } catch (UnknownHostException e) {
            log.warn("Unknown host for " + getLabel(), e);//$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        } catch (IOException e) {
            log.warn("Could not create socket for " + getLabel(), e); //$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        }
    }
    // (re-)Define connection params - Bug 50977 
    try {
        con.setSoTimeout(getTimeout());
        con.setTcpNoDelay(getNoDelay());
        if (log.isDebugEnabled()) {
            log.debug(this + "  Timeout " + getTimeout() + " NoDelay " + getNoDelay()); //$NON-NLS-1$
        }
    } catch (SocketException se) {
        log.warn("Could not set timeout or nodelay for " + getLabel(), se); //$NON-NLS-1$
        cp.put(ERRKEY, se.toString());
    }
    return con;
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** Setup all socket options.  Should be called before any read/write
 * calls *///ww  w  .  j  a  va  2s  .  c o  m
void setupOpenSocket(Socket sock) throws SocketException {
    if (log.isDebug3()) {
        log.debug3(sock + "SO_TIMEOUT: " + getSoTimeout() + ", TcpNoDelay: " + isTcpNoDelay() + ", KeepAlive: "
                + paramSoKeepAlive);
    }
    sock.setSoTimeout((int) getSoTimeout());
    sock.setTcpNoDelay(isTcpNoDelay());
    sock.setKeepAlive(paramSoKeepAlive);
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in blocking mode.//from w  ww.  j  ava  2  s.c  om
 * @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 2  s .  c om*/
 * @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
}