Search in sources :

Example 66 with SelectionKey

use of java.nio.channels.SelectionKey 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 67 with SelectionKey

use of java.nio.channels.SelectionKey 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 68 with SelectionKey

use of java.nio.channels.SelectionKey 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 69 with SelectionKey

use of java.nio.channels.SelectionKey in project CshBBrain by CshBBrain.

the class Worker method process.

public void process(Object selectKey) {
    if (selectKey instanceof SelectionKey) {
        SelectionKey selectionKey = (SelectionKey) selectKey;
        Client key = Client.getSockector(selectionKey);
        if (key.getMessages(charBuffer)) {
            // 已完成握手,从客户端读取报刊
            // 进行业务处理
            key.process();
        }
    } else if (selectKey instanceof Client) {
        // 直接发送消息
        ((Client) selectKey).send();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Example 70 with SelectionKey

use of java.nio.channels.SelectionKey in project CshBBrain by CshBBrain.

the class MasterServer method startClustersMonitor.

/**
	 * 
	 * <li>方法名:startClustersMonitor
	 * <li>
	 * <li>返回类型:void
	 * <li>说明:开始监听集群服务器节点中的连接请求
	 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/
	 * <li>创建日期:2012-10-21
	 * <li>修改人: 
	 * <li>修改日期:
	 */
private void startClustersMonitor() {
    try {
        // Create a new selector
        Selector selector = Selector.open();
        // Create a new non-blocking server socket channel
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        // 集群端口
        InetSocketAddress isa = new InetSocketAddress(this.clustersPort);
        serverChannel.socket().bind(isa);
        // Register the server socket channel, indicating an interest in 
        // accepting new connections
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        log.info("集群服务器准备就绪,等待集群请求到来");
        while (noStopRequested) {
            try {
                int num = 0;
                // Wait for an event one of the registered channels
                num = selector.select(100);
                if (num > 0) {
                    // Iterate over the set of keys for which events are available
                    Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
                    while (selectedKeys.hasNext()) {
                        SelectionKey key = (SelectionKey) selectedKeys.next();
                        selectedKeys.remove();
                        if (!key.isValid()) {
                            continue;
                        }
                        // Check what event is available and deal with it
                        if (key.isAcceptable()) {
                            // 注册集群连接
                            this.accept(key, true);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 关闭服务器
        serverChannel.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Clusters Server start up fail");
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5