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.dbay.apns4j.impl.ApnsConnectionImpl.java

private Socket createNewSocket() throws IOException, UnknownHostException {
    if (logger.isDebugEnabled()) {
        logger.debug(connName + " create a new socket.");
    }/*  www .j  a v a 2s .  c o m*/
    isFirstWrite = true;
    errorHappendedLastConn = false;
    Socket socket = factory.createSocket(host, port);
    socket.setSoTimeout(readTimeOut);
    // enable tcp_nodelay, any data will be sent immediately.
    socket.setTcpNoDelay(true);

    return socket;
}

From source file:org.apache.axis2.transport.http.server.AxisHttpConnectionImpl.java

public AxisHttpConnectionImpl(final Socket socket, final HttpParams params) throws IOException {
    super();//from  www .ja  v  a  2s .c  o m
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

    int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }

    int buffersize = HttpConnectionParams.getSocketBufferSize(params);
    this.socket = socket;
    this.outbuffer = new SocketOutputBuffer(socket, buffersize, params);
    this.inbuffer = new SocketInputBuffer(socket, buffersize, params);
    this.contentLenStrategy = new StrictContentLengthStrategy();
    this.requestParser = new HttpRequestParser(this.inbuffer, null, new DefaultHttpRequestFactory(), params);
    this.responseWriter = new HttpResponseWriter(this.outbuffer, null, params);
}

From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java

public VenusBIOConnection makeObject() throws Exception {
    Socket socket = new Socket();
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {/*w  ww. ja  v a 2s  .  com*/
        address = new InetSocketAddress(host, port);
    }

    socket.setSendBufferSize(sendBufferSize * 1024);
    socket.setReceiveBufferSize(receiveBufferSize * 1024);
    socket.setTcpNoDelay(tcpNoDelay);
    socket.setKeepAlive(keepAlive);
    try {
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }
        if (coTimeout > 0) {
            socket.connect(address, coTimeout);
        } else {
            socket.connect(address);
        }
    } catch (ConnectException e) {
        throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort());
    }

    VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis());
    byte[] bts = conn.read();
    HandshakePacket handshakePacket = new HandshakePacket();
    handshakePacket.init(bts);

    AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket);
    conn.write(authen.toByteArray());
    bts = conn.read();
    int type = AbstractServicePacket.getType(bts);
    if (type == PacketConstant.PACKET_TYPE_OK) {
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success");
        }
    } else if (type == PacketConstant.PACKET_TYPE_ERROR) {
        ErrorPacket error = new ErrorPacket();
        error.init(bts);
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code="
                    + error.errorCode + ",message=" + error.message + "}");
        }
        throw new AuthenticationException(error.message, error.errorCode);
    }

    return conn;
}

From source file:org.squidy.nodes.iPhone.java

/**
 *
 *//*from  w  w  w  .jav  a 2s  .  co  m*/
private void startTCPServer() {
    new Thread() {
        @Override
        public void run() {
            try {
                tcpServer = new ServerSocket(port + 1);

                while (isProcessing()) {
                    Socket client = tcpServer.accept();
                    client.setTcpNoDelay(true);

                    outputStreams.put(client, new DataOutputStream(client.getOutputStream()));
                }
            } catch (IOException e) {
                // publishFailure(e);
            }
        }
    }.start();
}

From source file:com.feedzai.fos.impl.weka.WekaManager.java

/**
 * Create a new manager from the given configuration.
 * <p/> Will lookup any headers files and to to instantiate the model.
 * <p/> If a model fails, a log is produced but loading other models will continue (no exception is thrown).
 *
 * @param wekaManagerConfig the manager configuration
 *//*from  ww  w . j a va2 s.  c  om*/
public WekaManager(WekaManagerConfig wekaManagerConfig) {
    checkNotNull(wekaManagerConfig, "Manager config cannot be null");

    this.wekaManagerConfig = wekaManagerConfig;

    Collection<File> headers = FileUtils.listFiles(wekaManagerConfig.getHeaderLocation(),
            new String[] { WekaManagerConfig.HEADER_EXTENSION }, true);
    for (File header : headers) {
        logger.trace("Reading model file '{}'", header);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(header);
            String modelConfigJson = IOUtils.toString(fileInputStream);

            ModelConfig modelConfig = mapper.readValue(modelConfigJson, ModelConfig.class);
            WekaModelConfig wekaModelConfig = new WekaModelConfig(modelConfig, wekaManagerConfig);
            wekaModelConfig.setHeader(header);
            wekaModelConfig.setDirty(false /* not changed so far */);

            if (modelConfigs.containsKey(wekaModelConfig.getId())) {
                logger.error(
                        "Model with ID '{}' is duplicated in the configuration (the configuration from '{}' is discarded)",
                        wekaModelConfig.getId(), header.getAbsolutePath());
            } else {
                modelConfigs.put(wekaModelConfig.getId(), wekaModelConfig);
            }
        } catch (Exception e) {
            logger.error("Could not load from '{}' (continuing to load others)", header, e);
        } finally {
            IOUtils.closeQuietly(fileInputStream);
        }
    }

    this.wekaScorer = new WekaScorer(modelConfigs, wekaManagerConfig);

    try {
        int port = wekaManagerConfig.getScoringPort();
        this.serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);
        final int max_threads = wekaManagerConfig.getMaxSimultaneousScoringThreads();
        Runnable acceptRunnable = new Runnable() {
            ExecutorService executor = Executors.newFixedThreadPool(max_threads);

            @Override
            public void run() {
                acceptThreadRunning = true;
                try {
                    while (acceptThreadRunning && Thread.currentThread().isInterrupted() == false) {
                        Socket client = serverSocket.accept();
                        client.setTcpNoDelay(true);
                        scorerHandler = new KryoScoringEndpoint(client, wekaScorer);
                        executor.submit(scorerHandler);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        };
        acceptThread = new Thread(acceptRunnable);
        acceptThread.start();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java

/**
 * Handle Job. Implementation of ThreadPool.handle(), calls handleConnection.
 * /*from   w  w w  . j  a  v  a  2s.co m*/
 * @param job A Connection.
 */
public void handle(Object job) {
    Socket socket = (Socket) job;
    try {
        if (_tcpNoDelay)
            socket.setTcpNoDelay(true);
        handleConnection(socket);
    } catch (Exception e) {
        log.debug("Connection problem", e);
    } finally {
        try {
            socket.close();
        } catch (Exception e) {
            log.debug("Connection problem", e);
        }
    }
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams httpConnectionParams)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (httpConnectionParams == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but HTTP connection parameters is null");
        throw new IllegalArgumentException("HTTP connection parameters cannot be null");
    }// w  w  w  . ja  va2  s.com

    Socket socket = getSslContext().getSocketFactory().createSocket();
    SocketAddress localSocketAddress = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteSocketAddress = new InetSocketAddress(host, port);

    socket.setSoTimeout(httpConnectionParams.getSoTimeout());
    if (httpConnectionParams.getLinger() > 0) {
        socket.setSoLinger(true, httpConnectionParams.getLinger());
    } else {
        socket.setSoLinger(false, 0);
    }
    socket.setTcpNoDelay(httpConnectionParams.getTcpNoDelay());
    if (httpConnectionParams.getSendBufferSize() >= 0) {
        socket.setSendBufferSize(httpConnectionParams.getSendBufferSize());
    }
    if (httpConnectionParams.getReceiveBufferSize() >= 0) {
        socket.setReceiveBufferSize(httpConnectionParams.getReceiveBufferSize());
    }

    socket.bind(localSocketAddress);
    socket.connect(remoteSocketAddress, httpConnectionParams.getConnectionTimeout());
    return socket;
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Sets socket attributes on the socket.
 * @param socket The socket./*from  w  ww . j  av a 2 s .  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);
}

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:com.linuxbox.enkive.server.AbstractSocketServer.java

public void run() {
    Socket sessionSocket = null;
    boolean hasSocket = false;
    try {/* ww  w.  j  a  v a  2  s  .c  o  m*/
        serverSocket = new ServerSocket(port, LISTEN_BACKLOG);
        serverSocket.setReceiveBufferSize(8);
        hasSocket = true;

        while (!hasShutdown()) {
            // TODO Eric : change this so there's a timeout and we can shut
            // down more cleanly than closing sockets out from under a
            // thread
            sessionSocket = serverSocket.accept(); // wait for connection

            // got connection!

            sessionSocket.setTcpNoDelay(true);

            createAndStartProcessor(sessionSocket);
            if (LOGGER.isTraceEnabled())
                LOGGER.trace(serviceName + " processor/session started");
        }
    } catch (SocketException e) {
        // will get a SocketException when the server socket is closed
        // LOGGER.debug("SocketException", e); catch it separately so it
        // isn't caught below in the catch for general exceptions
        if (!hasSocket) {
            LOGGER.error("unexpected socket exception", e);
        }
    } catch (Exception e) {
        LOGGER.error("Error running server or launching session.", e);
    } catch (Throwable e) {
        LOGGER.fatal("Unexpected error in server thread.", e);
    } finally {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(serviceName + " server has left run loop");
        }
    }

    shutdownProcessors();
}