关于selectionKey.iswritable()这方法的问题。他是测试此键的通道是否已准备好进行写入 如果此键的通道不支持写入操作,则此方法始终返回 false。 
那么我想知道的是:什么叫通道是否正被好进行写入??郁闷几天了。高手支招

解决方案 »

  1.   

    selectionKey.iswritable()没见过呀,哪个包里的
      

  2.   

    用异步输入输出流编写Socket进程通信程序 
    在Merlin中加入了用于实现异步输入输出机制的应用程序接口包:java.nio(新的输入输出包,定义了很多基本类型缓冲(Buffer)),java.nio.channels(通道及选择器等,用于异步输入输出),java.nio.charset(字符的编码解码)。通道(Channel)首先在选择器(Selector)中注册自己感兴趣的事件,当相应的事件发生时,选择器便通过选择键(SelectionKey)通知已注册的通道。然后通道将需要处理的信息,通过缓冲(Buffer)打包,编码/解码,完成输入输出控制。 通道介绍: 
    这里主要介绍ServerSocketChannel和 SocketChannel.它们都是可选择的(selectable)通道,分别可以工作在同步和异步两种方式下(注意,这里的可选择不是指可以选择两种工作方式,而是指可以有选择的注册自己感兴趣的事件)。可以用channel.configureBlocking(Boolean )来设置其工作方式。与以前版本的API相比较,ServerSocketChannel就相当于ServerSocket(ServerSocketChannel封装了ServerSocket),而SocketChannel就相当于Socket(SocketChannel封装了Socket)。当通道工作在同步方式时,编程方法与以前的基本相似,这里主要介绍异步工作方式。 所谓异步输入输出机制,是指在进行输入输出处理时,不必等到输入输出处理完毕才返回。所以异步的同义语是非阻塞(None Blocking)。在服务器端,ServerSocketChannel通过静态函数open()返回一个实例serverChl。然后该通道调用serverChl.socket().bind()绑定到服务器某端口,并调用register(Selector sel, SelectionKey.OP_ACCEPT)注册OP_ACCEPT事件到一个选择器中(ServerSocketChannel只可以注册OP_ACCEPT事件)。当有客户请求连接时,选择器就会通知该通道有客户连接请求,就可以进行相应的输入输出控制了;在客户端,clientChl实例注册自己感兴趣的事件后(可以是OP_CONNECT,OP_READ,OP_WRITE的组合),调用clientChl.connect(InetSocketAddress )连接服务器然后进行相应处理。注意,这里的连接是异步的,即会立即返回而继续执行后面的代码。 选择器和选择键介绍: 
    选择器(Selector)的作用是:将通道感兴趣的事件放入队列中,而不是马上提交给应用程序,等已注册的通道自己来请求处理这些事件。换句话说,就是选择器将会随时报告已经准备好了的通道,而且是按照先进先出的顺序。那么,选择器是通过什么来报告的呢?选择键(SelectionKey)。选择键的作用就是表明哪个通道已经做好了准备,准备干什么。你也许马上会想到,那一定是已注册的通道感兴趣的事件。不错,例如对于服务器端serverChl来说,可以调用key.isAcceptable()来通知serverChl有客户端连接请求。相应的函数还有:SelectionKey.isReadable(),SelectionKey.isWritable()。一般的,在一个循环中轮询感兴趣的事件(具体可参照下面的代码)。如果选择器中尚无通道已注册事件发生,调用Selector.select()将阻塞,直到有事件发生为止。另外,可以调用selectNow()或者select(long timeout)。前者立即返回,没有事件时返回0值;后者等待timeout时间后返回。一个选择器最多可以同时被63个通道一起注册使用。 
      

  3.   

    public class NBlockingServer { 
    int port = 8000; 
    int BUFFERSIZE = 1024; 
    Selector selector = null; 
    ServerSocketChannel serverChannel = null; 
    HashMap clientChannelMap = null;//用来存放每一个客户连接对应的套接字和通道 public NBlockingServer( int port ) { 
    this.clientChannelMap = new HashMap(); 
    this.port = port; 
    } public void initialize() throws IOException { 
    //初始化,分别实例化一个选择器,一个服务器端可选择通道 
    this.selector = Selector.open(); 
    this.serverChannel = ServerSocketChannel.open(); 
    this.serverChannel.configureBlocking(false); 
    InetAddress localhost = InetAddress.getLocalHost(); 
    InetSocketAddress isa = new InetSocketAddress(localhost, this.port ); 
    this.serverChannel.socket().bind(isa);//将该套接字绑定到服务器某一可用端口 

    //结束时释放资源 
    public void finalize() throws IOException { 
    this.serverChannel.close(); 
    this.selector.close(); 

    //将读入字节缓冲的信息解码 
    public String decode( ByteBuffer byteBuffer ) throws 
    CharacterCodingException { 
    Charset charset = Charset.forName( "ISO-8859-1" ); 
    CharsetDecoder decoder = charset.newDecoder(); 
    CharBuffer charBuffer = decoder.decode( byteBuffer ); 
    String result = charBuffer.toString(); 
    return result; 

    //监听端口,当通道准备好时进行相应操作 
    public void portListening() throws IOException, InterruptedException { 
    //服务器端通道注册OP_ACCEPT事件 
    SelectionKey acceptKey =this.serverChannel.register( this.selector, 
    SelectionKey.OP_ACCEPT ); 
    //当有已注册的事件发生时,select()返回值将大于0 
    while (acceptKey.selector().select() > 0 ) { 
    System.out.println("event happened"); 
    //取得所有已经准备好的所有选择键 
    Set readyKeys = this.selector.selectedKeys(); 
    //使用迭代器对选择键进行轮询 
    Iterator i = readyKeys.iterator(); 
    while (i 
    else if ( key.isReadable() ) {//如果是通道读准备好事件 
    System.out.println("Readable"); 
    //取得选择键对应的通道和套接字 
    SelectableChannel nextReady = 
    (SelectableChannel) key.channel(); 
    Socket socket = (Socket) key.attachment(); 
    //处理该事件,处理方法已封装在类ClientChInstance中 
    this.readFromChannel( socket.getChannel(), 
    (ClientChInstance) 
    this.clientChannelMap.get( socket ) ); 

    else if ( key.isWritable() ) {//如果是通道写准备好事件 
    System.out.println("writeable"); 
    //取得套接字后处理,方法同上 
    Socket socket = (Socket) key.attachment(); 
    SocketChannel channel = (SocketChannel) 
    socket.getChannel(); 
    this.writeToChannel( channel,"This is from server!"); 




    //对通道的写操作 
    public void writeToChannel( SocketChannel channel, String message ) 
    throws IOException { 
    ByteBuffer buf = ByteBuffer.wrap( message.getBytes() ); 
    int nbytes = channel.write( buf ); 

    //对通道的读操作 
    public void readFromChannel( SocketChannel channel, ClientChInstance clientInstance ) 
    throws IOException, InterruptedException { 
    ByteBuffer byteBuffer = ByteBuffer.allocate( BUFFERSIZE ); 
    int nbytes = channel.read( byteBuffer ); 
    byteBuffer.flip(); 
    String result = this.decode( byteBuffer ); 
    //当客户端发出”@exit”退出命令时,关闭其通道 
    if ( result.indexOf( "@exit" ) >= 0 ) { 
    channel.close(); 

    else { 
    clientInstance.append( result.toString() ); 
    //读入一行完毕,执行相应操作 
    if ( result.indexOf( "\n" ) >= 0 ){ 
    System.out.println("client input"+result); 
    clientInstance.execute(); 



    //该类封装了怎样对客户端的通道进行操作,具体实现可以通过重载execute()方法 
    public class ClientChInstance { 
    SocketChannel channel; 
    StringBuffer buffer=new StringBuffer(); 
    public ClientChInstance( SocketChannel channel ) { 
    this.channel = channel; 

    public void execute() throws IOException { 
    String message = "This is response after reading from channel!"; 
    writeToChannel( this.channel, message ); 
    buffer = new StringBuffer(); 

    //当一行没有结束时,将当前字窜置于缓冲尾 
    public void append( String values ) { 
    buffer.append( values ); 


    //主程序 
    public static void main( String[] args ) { 
    NBlockingServer nbServer = new NBlockingServer(8000); 
    try { 
    nbServer.initialize(); 
    } catch ( Exception e ) { 
    e.printStackTrace(); 
    System.exit( -1 ); 

    try { 
    nbServer.portListening(); 

    catch ( Exception e ) { 
    e.printStackTrace(); 



      

  4.   

    八楼的同志辛苦你了。但是你说的和我问的好像联系不是很密切我想是 问 。。怎么来   判断是否可以读写.换句话说  isWritable() isReadable()如何猜为true...其他的东西不用解释
      

  5.   

    http://hi.baidu.com/ibwwbtf_jie/blog/item/b06a13b32d43c7a3d9335ac2.html
    可能有答案
      

  6.   

    ==============================================
    按照api里的说法 k.isWritable() ,该调用与以下调用的作用完全相同:  k.readyOps() & OP_WRITE != 0
    它的类里有一些状态的Flag来表明通道的状态
    不过本质上建立一个通道完成数据的交换,除了通过socket建立连接外,还要有输入输出流来执行具体的数据交换工作,这里的isWritable()还有isReadable()
    应该根据输入输出流的状态来判断的
    若输入流被关闭了自然不可写入,输出流关闭了自然不可读取了,更具体的我觉得就找jdk的源码去看看到底怎么回事
      

  7.   

    selectionKey k 
    k.isWritable() 等价 k.readyOps() & OP_WRITE != 0
    如果此键的通道不支持写入操作,则此方法始终返回 false。
    当且仅当 readyOps() & OP_WRITE 为非零值时才返回 true 
      

  8.   

    问题是读的数据由Client触发,而Write是我们Server主动要发.
    这里的主要问题不是简单的"readyOps() & OP_WRITE 为非零值时才返回 true"
    而是readyOps() 什么是否能够返回OP_WRITE 的问题.那么是否是SelectionKey有setReadyToWrite的方法,因为发送是我们主动控制的.
      

  9.   

    9楼的代码中
    else if ( key.isWritable() ) {//如果是通道写准备好事件 
    System.out.println("writeable"); 
    //取得套接字后处理,方法同上 
    Socket socket = (Socket) key.attachment(); 
    SocketChannel channel = (SocketChannel) 
    socket.getChannel(); 
    this.writeToChannel( channel,"This is from server!"); 
    } 什么时候执行?什么条件下key.isWritable() == true?9楼代码的模型是一个Ask-Response模型,Client发送byte指令(不是exit),那么Server调用clientInstance.execute();

    public void execute() throws IOException 

    String message = "This is response after reading from channel!"; 
    writeToChannel( this.channel, message ); 
    buffer = new StringBuffer(); 
    }怎么ClientChInstance是NBlockingServer的内部类?内部类可以有public吗?
    writeToChannel就是NBlockingServer的writeToChannel方法吧(Java内部类可以直接访问NBlockingServer的方法吗?感觉好象是不可以的)
    看代码来说ClientChInstance.exectue中的writeToChannel就是NBlockingServer的writeToChannel.
    那writeToChannel已经被直接调用过了,那else if ( key.isWritable() ) 更是奇怪了?更本没调用到了,else if ( key.isWritable() )里也是调用
    writeToChannel,总不能是writeToChannel导致key.isWritable() 为true,而else if ( key.isWritable() )内也调用writeToChannel,成为死循环了.
      

  10.   

    关于selectionKey.iswritable()这方法的问题。他是测试此键的通道是否已准备好进行写就绪 如果此键的通道不支持写入操作,则此方法始终返回 false。我测试了下关于非阻塞通信程序,发现selection.isReadable()只有在客户端发送数据过来才为true;而selectionKey.iswritable()在客户端与服务器联通后,一直是为true的. 这里可能就是表示连接的客户端socket通道支持写入,所以它一直为true.
      

  11.   

    不是支持写入,而是客户端socket通道此时反馈告诉你允许写入(这样可能更贴切点)
      

  12.   

    在主轮询的程序中是阻塞的,下面代码
         while(true){
                                Set readyKeys = selector.selectedKeys();
    Iterator it = readyKeys.iterator();
    while (it.hasNext()) {
    SelectionKey key = null;
    try {
    key = (SelectionKey) it.next();
    it.remove();
    if (key.isReadable()) {// 判断是否可读操作
    receive(key);
    }
    if (key.isWritable()) {// 判断是否可写操作
    send(key);
    }
    } catch (IOException e) {
    e.printStackTrace();
    try {
    if (key != null) {
    key.cancel();
    key.channel().close();
    }
    } catch (Exception ex) {
    e.printStackTrace();
    }
    } }// #while
         }//#while    第一层while循环是一个死循环,会取出所有已经注册的SelectionKey,并且逐个判断key的各种状态,如果处理某个状态下,就可以执行相应的方法。
      

  13.   

      就是判断可读,可写,你可以打印输出这个几个值,你会发现,当server端通过通道返回数据给客户端的时候,isReadable为true,其他情况一律为false,而iswritable一直为true,因为客户端随时随刻都会有可能给服务器端发送数据,而服务器端则未必。
      

  14.   

    作为c/c++程序员,对于java就有一种践踏的冲动,算了,还是说正事。
    我最近用nio也发现,有消息需要读时readable才为真,但是writable几乎一直为真,后来研究了一下发现这跟系统的实现有关。
    对于读操作,只有当网络数据进入操作系统内核,即数据进入socket的内核缓冲区,此时在那个socket上睡眠的线程才会被唤醒,就是说从selector()醒来,此时因为数据可读,所以readable判断为真。
    至于写操作,os的做法分两步,第一步把应用程序的数据拷贝到内核中的socket缓冲区去,第二步才执行tcp/ip进行网络传输。重点来了,我们的send函数其实只保证第一步,意思是说只要数据被拷贝到内核中,就认为send完成了,就立即返回了,而此时可能数据根本没有传输出去。所以send通常不会阻塞,而是立即完成。send被阻塞只可能是因为socket的内核缓冲用完了,比如好几次send操作把buffer堆满了,而数据还没实际发送到对端主机。