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.l2jfree.gameserver.network.L2ClientSelectorThread.java

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

    if (!Config.CONNECTION_FILTERING || !LoginServerThread.getInstance().supportsNewLoginProtocol())
        return true;

    final String ip = sc.socket().getInetAddress().getHostAddress();

    final Integer count = _legalConnections.get(ip);

    if (count == null)
        return false;

    if (count == 1)
        _legalConnections.remove(ip);/*from   w  w w. jav a2 s .  co  m*/
    else
        _legalConnections.put(ip, count - 1);
    return true;
}

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

public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException {
    final SocketChannel channel;
    try {//from   w w  w .ja v  a 2 s  .  c  om
        channel = SocketChannel.open();
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }
    final Socket socket = channel.socket();
    try {
        SocketUtils.openSocket(socket, sockAddr, 0, 2000L, 3);
    } catch (IOException e) {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }

    final ByteBuffer buf = toBuffer(msg);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining()
                + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']');
    }
    final int written;
    try {
        written = NIOUtils.countingWriteFully(channel, buf);
        NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN)
    } catch (IOException ioe) {
        final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr
                + ']';
        LOG.error(errmsg, ioe);
        throw new GridException(errmsg, ioe);
    } catch (Throwable e) {
        LOG.fatal(e.getMessage(), e);
        throw new GridException("Unexpected exception was caused", e);
    } finally {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr
                + "]");
    }
}

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

/**
 * Process the contents that have been read into the buffer. Allow sub-classes to override this behavior.
 *
 * @param socketChannel the channel the data was read from
 * @param socketBuffer the buffer the data was read into
 * @throws InterruptedException if interrupted when queuing events
 *//*from w  w w  . j  a v  a2  s.  c om*/
protected void processBuffer(final SocketChannel socketChannel, final ByteBuffer socketBuffer)
        throws InterruptedException, IOException {
    // get total bytes in buffer
    final int total = socketBuffer.remaining();
    final InetAddress sender = socketChannel.socket().getInetAddress();

    // go through the buffer looking for the end of each message
    currBytes.reset();
    for (int i = 0; i < total; i++) {
        // NOTE: For higher throughput, the looking for \n and copying into the byte stream could be improved
        // Pull data out of buffer and cram into byte array
        byte currByte = socketBuffer.get();

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

                // Mark this as the start of the next message
                socketBuffer.mark();
            }
        } else {
            currBytes.write(currByte);
        }
    }
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {/*from   www.j  a  va 2  s.com*/
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void configureChannel(SocketChannel channel) throws IOException {
    channel.configureBlocking(false);// ww w  .  ja  va2 s. c  o  m
    channel.socket().setSendBufferSize(0x100000); // 1Mb
    channel.socket().setReceiveBufferSize(0x100000); // 1Mb
    channel.socket().setKeepAlive(true);
    channel.socket().setReuseAddress(true);
    channel.socket().setSoLinger(false, 0);
    channel.socket().setSoTimeout(0);
    channel.socket().setTcpNoDelay(true);
}

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

/**
 * An easy way to apply any special limitations on incoming connections. At default it contains
 * a flood protection.<br>//from   www .j  a v a  2  s.  co m
 * Overriding implementations should call the super method before anything else gets checked.<br>
 * <br>
 * NOTE: Uses a special way of logging to avoid console flood.
 * 
 * @param sc the inbound connection from a possible client
 * @return true if the connection is valid, and should be allowed, no otherwise
 */
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;
    }
    case WARNED: {
        // TODO punish, warn, log, etc
        _log.warn("Connection over warn limit from " + host);
        return true;
    }
    default:
        return true;
    }
}

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

private void acceptConnection(SelectionKey key) {
    SocketChannel sc;
    try {/*www .  j  av a  2 s  .co  m*/
        while ((sc = ((ServerSocketChannel) key.channel()).accept()) != null) {
            if (getMMOController().acceptConnectionFrom(sc)) {
                sc.configureBlocking(false);

                Util.printSection(getMMOController().getClass().getSimpleName() + " "
                        + sc.socket().getRemoteSocketAddress().toString());
                final T con = getMMOController().createClient(sc);
                con.enableReadInterest();
            } else {
                IOUtils.closeQuietly(sc.socket());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.devoteam.srit.xmlloader.http.nio.NIOSocketServerListener.java

public void acceptReady() {
    try {//from  w  w w  . j  a v a2s.co m
        SocketChannel socketChannel = this.channel.accept();

        NIOSocketServerHttp socketServerHttp = new NIOSocketServerHttp();
        HybridSocket socket = new HybridSocket(socketServerHttp);

        InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socketChannel.socket()
                .getRemoteSocketAddress();
        InetSocketAddress localInetSocketAddress = (InetSocketAddress) socketChannel.socket()
                .getLocalSocketAddress();

        String connectionName = "HTTPServerConnection" + Stack.nextTransactionId();
        String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress();
        String remotePort = Integer.toString(remoteInetSocketAddress.getPort());
        String localHost = localInetSocketAddress.getAddress().getHostAddress();
        String localPort = Integer.toString(localInetSocketAddress.getPort());

        NIOChannelHttp channelHTTP = new NIOChannelHttp(connectionName, localHost, localPort, remoteHost,
                remotePort, StackFactory.PROTOCOL_HTTP, secure);

        DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();

        socketServerHttp.init(serverConnection, channelHTTP);

        channelHTTP.setSocketServerHttp(socketServerHttp);
        StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(channelHTTP);
        if (socketChannel instanceof SSLSocketChannel)
            StackHttp.ioReactor.openTLS((SSLSocketChannel) socketChannel, socket);
        else
            StackHttp.ioReactor.openTCP(socketChannel, socket);

        serverConnection.bind(socket, new BasicHttpParams());
    } catch (Exception e) {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e,
                "Exception in SocketServerListener secure=", secure);
        e.printStackTrace();
    }
}

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

public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException {
    final SocketChannel channel;
    try {/*from  w w w  . ja va 2 s  .c om*/
        channel = SocketChannel.open();
        channel.configureBlocking(false);
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }
    final Socket socket = channel.socket();
    try {
        socket.connect(sockAddr);
        // wait for connect succeeds
        while (!channel.finishConnect()) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                ;
            }
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }

    final ByteBuffer buf = toBuffer(msg);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining()
                + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']');
    }
    final int written;
    try {
        written = NIOUtils.countingWriteFully(channel, buf);
        NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN)
    } catch (IOException ioe) {
        final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr
                + ']';
        LOG.error(errmsg, ioe);
        throw new GridException(errmsg, ioe);
    } catch (Throwable e) {
        LOG.fatal(e.getMessage(), e);
        throw new GridException("Unexpected exception was caused", e);
    } finally {
        NetUtils.closeQuietly(socket);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr
                + "]");
    }
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {/* w w  w.  ja  v  a 2 s .c o  m*/
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}