Search in sources :

Example 36 with SocketChannel

use of java.nio.channels.SocketChannel in project robo4j by Robo4J.

the class HttpClientUnit method onMessage.

@Override
public void onMessage(Object message) {
    try {
        SocketChannel client = SocketChannel.open(address);
        client.configureBlocking(true);
        ByteBuffer buffer = ByteBuffer.wrap(((String) message).getBytes());
        int c = client.write(buffer);
        if (responseUnit != null && responseSize != null) {
            ByteBuffer readBuffer = ByteBuffer.allocate(responseSize);
            client.read(readBuffer);
            sendMessageToResponseUnit(readBuffer);
        }
        client.close();
    } catch (IOException e) {
        throw new HttpException("onMessage", e);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 37 with SocketChannel

use of java.nio.channels.SocketChannel in project runesource by PureCS.

the class Server method accept.

/**
     * Accepts any incoming connections.
     *
     * @throws IOException
     */
private void accept() throws IOException {
    SocketChannel socket;
    /*
         * Here we use a for loop so that we can accept multiple clients per
		 * tick for lower latency. We limit the amount of clients that we
		 * accept per tick to better combat potential denial of service type
		 * attacks.
		 */
    for (int i = 0; i < 10; i++) {
        socket = serverChannel.accept();
        if (socket == null) {
            // No more connections to accept (as this one was invalid).
            break;
        }
        // Register the connection
        HostGateway.enter(socket.socket().getInetAddress().getHostAddress());
        // Set up the new connection.
        socket.configureBlocking(false);
        SelectionKey key = socket.register(selector, SelectionKey.OP_READ);
        Client client = new Player(key);
        System.out.println("Accepted " + client + ".");
        getClientMap().put(key, client);
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) Player(com.rs.entity.player.Player) Client(com.rs.entity.player.Client)

Example 38 with SocketChannel

use of java.nio.channels.SocketChannel in project yyl_example by Relucent.

the class Receive method main.

public static void main(String[] args) throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    ServerSocketChannel ss = ServerSocketChannel.open();
    ss.socket().bind(new InetSocketAddress(9998));
    ss.configureBlocking(false);
    Selector se = Selector.open();
    ss.register(se, SelectionKey.OP_ACCEPT);
    while (se.select() > 0) {
        Set<SelectionKey> set = se.selectedKeys();
        for (SelectionKey key : set) {
            System.out.println("-------------");
            SocketChannel sc = null;
            try {
                if (key.isAcceptable()) {
                    sc = ss.accept();
                    System.err.println("ACCEPTABLE:" + sc.socket());
                    sc.configureBlocking(false);
                    sc.register(se, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    sc = (SocketChannel) key.channel();
                    System.out.println(sc.isConnected());
                    sc.read(buffer);
                    buffer.flip();
                    System.out.println(new String(buffer.array(), 0, buffer.remaining()));
                    sc.write(ByteBuffer.wrap("+".getBytes()));
                }
            } catch (Exception e) {
                key.cancel();
                if (sc != null) {
                    sc.close();
                }
                e.printStackTrace();
            }
        }
        set.clear();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 39 with SocketChannel

use of java.nio.channels.SocketChannel in project yyl_example by Relucent.

the class Send method main.

public static void main(String[] args) throws Exception {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    Selector selector = Selector.open();
    socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    socketChannel.connect(new InetSocketAddress("127.0.0.1", 9998));
    while (!socketChannel.finishConnect()) {
    }
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    socketChannel.write(ByteBuffer.wrap("-".getBytes()));
    int index = 0;
    while (true) {
        if (selector.select() == 0) {
            Thread.sleep(1000);
            continue;
        }
        Set<SelectionKey> set = selector.selectedKeys();
        for (SelectionKey key : set) {
            int ops = key.readyOps();
            if ((ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                socketChannel.write(buffer);
                System.out.println("OP_CONNECT:");
            }
            if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                socketChannel.read(buffer);
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, buffer.remaining()));
                buffer.clear();
                socketChannel.write(ByteBuffer.wrap(("No-" + index + " | ").getBytes()));
                index++;
            }
        }
        set.clear();
        Thread.sleep(1000);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 40 with SocketChannel

use of java.nio.channels.SocketChannel in project CloudStack-archive by CloudStack-extras.

the class NioConnection method closeConnection.

protected void closeConnection(SelectionKey key) {
    if (key != null) {
        SocketChannel channel = (SocketChannel) key.channel();
        key.cancel();
        try {
            if (channel != null) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Closing socket " + channel.socket());
                }
                channel.close();
            }
        } catch (IOException ignore) {
        }
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) IOException(java.io.IOException)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)759 ServerSocketChannel (java.nio.channels.ServerSocketChannel)337 IOException (java.io.IOException)321 InetSocketAddress (java.net.InetSocketAddress)228 ByteBuffer (java.nio.ByteBuffer)188 SelectionKey (java.nio.channels.SelectionKey)126 Socket (java.net.Socket)101 Test (org.junit.Test)87 ClosedChannelException (java.nio.channels.ClosedChannelException)63 ServerSocket (java.net.ServerSocket)49 Selector (java.nio.channels.Selector)48 SocketAddress (java.net.SocketAddress)36 ClosedSelectorException (java.nio.channels.ClosedSelectorException)33 ConnectException (java.net.ConnectException)27 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ArrayList (java.util.ArrayList)27 SocketTimeoutException (java.net.SocketTimeoutException)25 SelectableChannel (java.nio.channels.SelectableChannel)23 HashMap (java.util.HashMap)23 OutputStream (java.io.OutputStream)22