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:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }//from  w w  w  .j  a v a  2  s . com
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();/*w  w w  .  ja  va  2s . c om*/
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleAccept(final ServerSocketChannel serverChannel, final Selector selector)
        throws IOException {
    final SocketChannel channel = serverChannel.accept();
    if (channel == null) {
        return;/*from  www. jav  a  2s.  co m*/
    }
    channel.configureBlocking(false);
    channel.register(selector, SelectionKey.OP_READ, new GridMessageBuffer());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Accepted a new client connection: " + channel.socket().getRemoteSocketAddress());
    }
}

From source file:gridool.communication.transport.tcp.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();/*from w ww  .  j ava2 s  . c om*/
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private static void writeToSocket(SocketChannel client, byte[] bytes) throws IOException {
    client.write(ByteBuffer.wrap(bytes));
    client.socket().getOutputStream().flush();
}

From source file:org.springframework.boot.devtools.tunnel.server.SocketTargetServerConnection.java

@Override
public ByteChannel open(int socketTimeout) throws IOException {
    SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
    logger.trace("Opening tunnel connection to target server on " + address);
    SocketChannel channel = SocketChannel.open(address);
    channel.socket().setSoTimeout(socketTimeout);
    return new TimeoutAwareChannel(channel);
}

From source file:org.pvalsecc.comm.ServerConnection.java

private Socket getSocket() {
    SocketChannel channel = (SocketChannel) key.channel();
    return channel.socket();
}

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

ContentStreamState(TcpReader stream) {
    super(stream);
    SocketChannel socketChannel = stream.getStream();
    InetSocketAddress remoteAddress = (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress();
    String remoteHost = remoteAddress.getHostName();
    streamContext_ = StreamContextManager.getStreamContext(remoteHost);
    streamStatus_ = StreamContextManager.getStreamStatus(remoteHost);
}

From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java

@SuppressWarnings("unchecked")
protected INioSession __doSessionCreate(IClientCfg cfg) throws IOException {
    SocketChannel _channel = SocketChannel.open();
    _channel.configureBlocking(false);/*from   w w w  . ja  va 2  s  .com*/
    _channel.socket().setReuseAddress(true);
    _channel.connect(new InetSocketAddress(cfg.getRemoteHost(), cfg.getPort()));
    __channel = _channel;
    return new NioSession(this, _channel);
}

From source file:com.l2jfree.mmocore.network.SelectorThread.java

protected boolean acceptConnectionFrom(SocketChannel sc) {
    final String host = sc.socket().getInetAddress().getHostAddress();

    final Result isFlooding = _accepts.isFlooding(host, true);

    switch (isFlooding) {
    case REJECTED: {
        // TODO: punish, warn, log, etc
        _log.warn("Rejected connection from " + host);
        return false;
    }/* w w w  . ja v  a 2 s. co  m*/
    case WARNED: {
        // TODO: punish, warn, log, etc
        _log.warn("Connection over warn limit from " + host);
        return true;
    }
    default:
        return true;
    }
}