Example usage for java.net Socket getChannel

List of usage examples for java.net Socket getChannel

Introduction

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

Prototype

public SocketChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.SocketChannel SocketChannel object associated with this socket, if any.

Usage

From source file:org.apache.hadoop.hdfs.net.TcpPeerServer.java

public static Peer peerFromSocket(Socket socket) throws IOException {
    Peer peer = null;/*from  w  w  w  . ja  v a  2 s . c om*/
    boolean success = false;
    try {
        // TCP_NODELAY is crucial here because of bad interactions between
        // Nagle's Algorithm and Delayed ACKs. With connection keepalive
        // between the client and DN, the conversation looks like:
        //   1. Client -> DN: Read block X
        //   2. DN -> Client: data for block X
        //   3. Client -> DN: Status OK (successful read)
        //   4. Client -> DN: Read block Y
        // The fact that step #3 and #4 are both in the client->DN direction
        // triggers Nagling. If the DN is using delayed ACKs, this results
        // in a delay of 40ms or more.
        //
        // TCP_NODELAY disables nagling and thus avoids this performance
        // disaster.
        socket.setTcpNoDelay(true);
        SocketChannel channel = socket.getChannel();
        if (channel == null) {
            peer = new BasicInetPeer(socket);
        } else {
            peer = new NioInetPeer(socket);
        }
        success = true;
        return peer;
    } finally {
        if (!success) {
            if (peer != null)
                peer.close();
            socket.close();
        }
    }
}

From source file:org.apache.hama.util.BSPNetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a
 * local address and port to bind the socket to.
 * //w w  w .  ja  v  a 2 s . c  om
 * @param socket
 * @param endpoint the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        socket.bind(localAddr);
    }

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:org.apache.jxtadoop.net.NetUtils.java

/**
 * This is a drop-in replacement for //from   w w w  .j ava 2s. com
 * {@link Socket#connect(SocketAddress, int)}.
 * In the case of normal sockets that don't have associated channels, this 
 * just invokes <code>socket.connect(endpoint, timeout)</code>. If 
 * <code>socket.getChannel()</code> returns a non-null channel,
 * connect is implemented using Hadoop's selectors. This is done mainly
 * to avoid Sun's connect implementation from creating thread-local 
 * selectors, since Hadoop does not have control on when these are closed
 * and could end up taking all the available file descriptors.
 * 
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * 
 * @param socket
 * @param endpoint 
 * @param timeout - timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

public InputStream getInputStream(Socket socket) throws IOException {
    return new ChannelInputStream(socket.getChannel());
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

public OutputStream getOutputStream(Socket socket) throws IOException {
    return new ChannelOutputStream(socket.getChannel());
}

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

/**
 * Starts server in blocking mode.//from  ww  w  . j  a  v  a2 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
}