Example usage for java.net Socket setReceiveBufferSize

List of usage examples for java.net Socket setReceiveBufferSize

Introduction

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

Prototype

public synchronized void setReceiveBufferSize(int size) throws SocketException 

Source Link

Document

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

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = "asdfasdfasdf\n";
    byte buf[] = str.getBytes();
    out.write(buf);/*from  w  ww  .j  a  va2  s  . c om*/
    int c;
    while ((c = in.read()) != -1) {
        System.out.print((char) c);
    }

    s.setReceiveBufferSize(1);

    s.close();
}

From source file:gridool.util.net.PoolableSocketChannelFactory.java

private static SocketChannel createSocketChannel(final SocketAddress sockAddr, final boolean blocking,
        final int rcvbufSize) {
    final SocketChannel ch;
    try {//from  w  w  w  . j a  v a  2 s .co m
        ch = SocketChannel.open();
        ch.configureBlocking(blocking);
    } catch (IOException e) {
        LOG.error("Failed to open SocketChannel.", e);
        throw new IllegalStateException(e);
    }
    final Socket sock = ch.socket();
    if (rcvbufSize != -1) {
        try {
            sock.setReceiveBufferSize(rcvbufSize);
        } catch (SocketException e) {
            LOG.error("Failed to setReceiveBufferSize.", e);
            throw new IllegalStateException(e);
        }
    }
    try {
        ch.connect(sockAddr);
    } catch (IOException e) {
        LOG.error("Failed to connect socket: " + sockAddr, e);
        throw new IllegalStateException(e);
    }
    return ch;
}

From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWSecureSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int,org.apache.commons.httpclient.params.HttpConnectionParams)
 *///from   w ww. jav  a  2  s .c  o m
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort,
        HttpConnectionParams params)
        throws IOException, UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException {

    Socket socket = createSocket(host, port, clientHost, clientPort);
    if (socket != null) {
        // socket.setKeepAlive(false);
        if (params.getReceiveBufferSize() >= 0)
            socket.setReceiveBufferSize(params.getReceiveBufferSize());
        if (params.getSendBufferSize() >= 0)
            socket.setSendBufferSize(params.getSendBufferSize());
        socket.setReuseAddress(true);
        if (params.getSoTimeout() >= 0)
            socket.setSoTimeout(params.getSoTimeout());
    }
    return socket;

}

From source file:com.smartwork.client.gsocket.CommonSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ServerAddress address = (ServerAddress) key;
    Socket conn = new Socket();
    conn.setSoTimeout(networkConfig.getReadTimeout() * 1000);
    conn.setTcpNoDelay(networkConfig.isTcpNoDelay());
    conn.setReuseAddress(networkConfig.isReuseAddress());
    conn.setSoLinger(networkConfig.getSoLinger() > 0, networkConfig.getSoLinger());
    conn.setSendBufferSize(networkConfig.getSendBufferSize());
    conn.setReceiveBufferSize(networkConfig.getReceiveBufferSize());
    conn.connect(new InetSocketAddress(address.getHost(), address.getPort()),
            networkConfig.getConnectTimeout() * 1000);
    return conn;/* w w  w  . j a  v a2s .c  o  m*/
}

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 {/*from ww w .jav a  2s. c  o  m*/
        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:com.lithium.flow.shell.sshj.SshjTunnel.java

private void accept(@Nonnull Socket socket) throws IOException {
    log.debug("connection from {}", socket.getRemoteSocketAddress());

    AbstractDirectChannel channel = new AbstractDirectChannel(connection, "direct-tcpip") {
        @Override/*from w w  w .j a v a 2  s  .  c  om*/
        @Nonnull
        protected SSHPacket buildOpenReq() {
            return super.buildOpenReq().putString(tunneling.getHost()).putUInt32(tunneling.getPort())
                    .putString(getHost()).putUInt32(server.getLocalPort());
        }
    };
    channel.open();

    socket.setSendBufferSize(channel.getLocalMaxPacketSize());
    socket.setReceiveBufferSize(channel.getRemoteMaxPacketSize());
    Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), channel.getOutputStream())
            .bufSize(channel.getRemoteMaxPacketSize()).spawnDaemon("soc2chan");
    Event<IOException> chan2soc = new StreamCopier(channel.getInputStream(), socket.getOutputStream())
            .bufSize(channel.getLocalMaxPacketSize()).spawnDaemon("chan2soc");
    SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, channel, socket);
}

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  .  j a  va2 s .  c om

    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:edu.hawaii.soest.kilonalu.tchain.TChainSource.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*//*from  w ww. j a  va2  s.com*/
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        Socket tcpSocket = dataSocket.socket();
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setReceiveBufferSize(40);
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {
        System.err.println("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        System.err.println("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

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);//  ww w  . ja va2s . co  m
    socket.setKeepAlive(connectorProperties.isKeepConnectionOpen());
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java

/** Open a connexion to each Stack */
public boolean open() throws Exception {
    if (this.secure) {
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {/*from www  . j  a  v a2 s  . co m*/
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }

    this.startTimestamp = System.currentTimeMillis();

    if (null != this.socketServerHttp) {
        ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp);
    } else {

        String host = this.getRemoteHost();
        int port = this.getRemotePort();

        DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection();

        Socket socket;

        if (this.secure) {
            // Create a trust manager that does not validate certificate chains like the default TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, null);

            socket = sslContext.getSocketFactory().createSocket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, true);
        } else {
            //
            // Create a TCP non secure socket
            //                
            socket = new Socket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, false);
        }

        //
        // Bind the socket to the local address
        //
        String localHost = this.getLocalHost();
        int localPort = initialLocalport;

        if (null != localHost) {
            socket.bind(new InetSocketAddress(localHost, localPort));
        } else {
            socket.bind(new InetSocketAddress(localPort));
        }

        socket.setReceiveBufferSize(65536);
        socket.connect(new InetSocketAddress(host, port));

        this.setLocalPort(socket.getLocalPort());

        HttpParams params = new BasicHttpParams();
        defaultHttpClientConnection.bind(socket, params);

        this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this);

        ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp);
    }
    return true;
}