Example usage for java.nio.channels SocketChannel socket

List of usage examples for java.nio.channels SocketChannel socket

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel socket.

Prototype

public abstract Socket socket();

Source Link

Document

Retrieves a socket associated with this channel.

Usage

From source file:com.facebook.infrastructure.net.io.ContentStreamState.java

public byte[] read() throws IOException, ReadNotCompleteException {
    SocketChannel socketChannel = stream_.getStream();
    InetSocketAddress remoteAddress = (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress();
    String remoteHost = remoteAddress.getHostName();
    createFileChannel();//from w ww.  j  av a 2s  .  c  om
    if (streamContext_ != null) {
        try {
            bytesRead_ += fc_.transferFrom(socketChannel, bytesRead_, ContentStreamState.count_);
            if (bytesRead_ != streamContext_.getExpectedBytes())
                throw new ReadNotCompleteException(
                        "Specified number of bytes have not been read from the Socket Channel");
        } catch (IOException ex) {
            /* Ask the source node to re-stream this file. */
            streamStatus_.setAction(StreamContextManager.StreamCompletionAction.STREAM);
            handleStreamCompletion(remoteHost);
            /* Delete the orphaned file. */
            File file = new File(streamContext_.getTargetFile());
            file.delete();
            throw ex;
        }
        if (bytesRead_ == streamContext_.getExpectedBytes()) {
            logger_.debug("Removing stream context " + streamContext_);
            handleStreamCompletion(remoteHost);
            bytesRead_ = 0L;
            fc_.close();
            morphState();
        }
    }

    return ArrayUtils.EMPTY_BYTE_ARRAY;
}

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

@Test
public void testBinary() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, true, false, nullPublisher, null);
    ChannelInputStream inputStream = TestUtils.getPropertyValue(connection, "channelInputStream",
            ChannelInputStream.class);
    inputStream.write(new byte[] { (byte) 0x80 }, 1);
    assertEquals(0x80, inputStream.read());
}

From source file:com.l2jfree.loginserver.network.L2ClientSelectorThread.java

@Override
public boolean acceptConnectionFrom(SocketChannel sc) {
    if (!super.acceptConnectionFrom(sc))
        return false;

    // Ignore permabanned IPs
    if (BanManager.getInstance().isRestrictedAddress(sc.socket().getInetAddress()))
        return false;

    return true;/*from   w  ww.  j  a v  a2s .  c  o m*/
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.SSLSocketChannelHandler.java

/**
 * Process the contents of the buffer. Give sub-classes a chance to override this behavior.
 *
 * @param sslSocketChannel the channel the data was read from
 * @param socketChannel the socket channel being wrapped by sslSocketChannel
 * @param bytesRead the number of bytes read
 * @param buffer the buffer to process/*from w  ww  . ja v  a 2s  .c o  m*/
 * @throws InterruptedException thrown if interrupted while queuing events
 */
protected void processBuffer(final SSLSocketChannel sslSocketChannel, final SocketChannel socketChannel,
        final int bytesRead, final byte[] buffer) throws InterruptedException, IOException {
    final InetAddress sender = socketChannel.socket().getInetAddress();

    // go through the buffer looking for the end of each message
    for (int i = 0; i < bytesRead; i++) {
        final byte currByte = buffer[i];

        // check if at end of a message
        if (currByte == getDelimiter()) {
            if (currBytes.size() > 0) {
                final SSLSocketChannelResponder response = new SSLSocketChannelResponder(socketChannel,
                        sslSocketChannel);
                final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString());
                final E event = eventFactory.create(currBytes.toByteArray(), metadata, response);
                events.offer(event);
                currBytes.reset();
            }
        } else {
            currBytes.write(currByte);
        }
    }
}

From source file:com.facebook.infrastructure.net.io.StartState.java

protected byte[] doRead(ByteBuffer buffer) throws IOException, ReadNotCompleteException {
    SocketChannel socketChannel = stream_.getStream();
    int bytesRead = socketChannel.read(buffer);
    if (bytesRead == -1 && buffer.remaining() > 0) {
        throw new IOException("Reached an EOL or something bizzare occured. Reading from: "
                + socketChannel.socket().getInetAddress() + " BufferSizeRemaining: " + buffer.remaining());
    }/*from w  w  w  . j  a  v a2s. co  m*/
    if (buffer.remaining() == 0) {
        morphState();
    } else {
        throw new ReadNotCompleteException(
                "Specified number of bytes have not been read from the Socket Channel");
    }
    return ArrayUtils.EMPTY_BYTE_ARRAY;
}

From source file:com.jilk.ros.rosbridge.implementation.ROSBridgeWebSocketClient.java

@Override
public void closeBlocking() throws InterruptedException {
    super.closeBlocking();
    try {// w  w w.  j  av a2s  . c  o  m
        Field channelField = this.getClass().getSuperclass().getDeclaredField("channel");
        channelField.setAccessible(true);
        SocketChannel channel = (SocketChannel) channelField.get(this);
        if (channel != null && channel.isOpen()) {
            Socket socket = channel.socket();
            if (socket != null)
                socket.close();
        }
    } catch (Exception ex) {
        System.out.println("Exception in Websocket close hack.");
        ex.printStackTrace();
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

private void doRead(SelectionKey key) {

    final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
    try {/*from   ww  w  .  j  av  a  2s  .c  o m*/
        incomingConnection.read();
    } catch (EOFException eof) {
        if (incomingConnection.isCloseUnexpected()) {
            final SocketChannel socketChannel = (SocketChannel) key.channel();
            LOG.error("Connection from " + socketChannel.socket().getRemoteSocketAddress()
                    + " was closed unexpectedly");
            incomingConnection.reportTransmissionProblem(key, eof);
        } else {
            incomingConnection.closeConnection(key);
        }
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(key, ioe);
    } catch (InterruptedException e) {
        // Nothing to do here
    } catch (NoBufferAvailableException e) {
        // There are no buffers available, unsubscribe from read event
        final SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            final SelectionKey newKey = socketChannel.register(this.selector, 0);
            newKey.attach(incomingConnection);
        } catch (ClosedChannelException e1) {
            incomingConnection.reportTransmissionProblem(key, e1);
        }

        final BufferAvailabilityListener bal = new IncomingConnectionBufferAvailListener(
                this.pendingReadEventSubscribeRequests, key);
        if (!e.getBufferProvider().registerBufferAvailabilityListener(bal)) {
            // In the meantime, a buffer has become available again, subscribe to read event again

            try {
                final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                newKey.attach(incomingConnection);
            } catch (ClosedChannelException e1) {
                incomingConnection.reportTransmissionProblem(key, e1);
            }
        }
    }
}

From source file:org.commoncrawl.io.internal.NIOClientTCPSocket.java

/** internal constructor used to create NIOSocket objects for incoming client connections **/
NIOClientTCPSocket(SocketChannel channel) throws IOException {
    _socketType = SocketType.Incoming;/*from ww  w  .j  av  a  2s.com*/
    _channel = channel;
    _address = new InetSocketAddress(channel.socket().getInetAddress(), channel.socket().getPort());
}

From source file:me.xingrz.prox.tcp.TcpProxy.java

/**
 * ? VPN  TCP ?????/*  w  ww.jav  a2 s.  c o m*/
 */
@Override
public void onAcceptable(SelectionKey key) {
    SocketChannel localChannel;

    try {
        localChannel = serverChannel.accept();
    } catch (IOException e) {
        logger.w(e, "Failed to accept client, ignored");
        return;
    }

    int sourcePort = localChannel.socket().getPort();

    TcpProxySession session = getSession(sourcePort);
    if (session == null) {
        logger.w("Ignored socket from %d without session", sourcePort);
        IOUtils.closeQuietly(localChannel);
        return;
    }

    logger.v("Accepted channel from %d, session %08x", sourcePort, session.hashCode());

    session.accept(localChannel);
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSessionManager.java

@Override
public Session newSession(NetWorkServer netWorkServer, SocketChannel channel, boolean start) {
    logger.info(new StringBuilder("New session for ")
            .append(channel.socket().getRemoteSocketAddress().toString()).toString());

    if (idleSessionList.isEmpty()) {
        increment();//  w  w  w .j  av  a 2s . c om
    }

    DefaultSession session = idleSessionList.remove(0);
    session.withNetWorkServer(netWorkServer).withChannel(channel).withCommandDispatcher(commandDispatcher)
            .withSlaveWorker(SlaveWorker.fromChannel(session.getId(), "Session-" + session.getId(), channel));

    if (start) {
        session.start();
    }
    sessionMap.put(session.getId(), session);
    // ?
    listener.sessionAllocated(session);
    return session;
}