Code example for SocketChannel

Methods: configureBlocking, connect, register

0
        System.out.println(" socket  initClient....ip:"+ip+",port:"+port+",userId:"+userId+",phone:"+phone);
        this.userId = userId;
        this.phone  = phone;
        this.name = name;
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(ip,port));
        channel.register(selector, SelectionKey.OP_CONNECT);
        return channel;
    } 
 
    /** 
     * 采用监听selector上是否有需要处理的事件,如果有,则进行处理 
     * @throws IOException 
     */ 
    @SuppressWarnings("unchecked") 
    public void listen() throws Exception { 
        while (pollFlag) {
            selector.select();
            Iterator ite = this.selector.selectedKeys().iterator();