在Client端的编写过程中发现了一个问题,就是: this.channel.connect(new InetSocketAddress(ip, port)); this.channel.configureBlocking(false);这两句话不能颠倒位置,颠倒了位置的话,我后面紧接着写了一步write操作就要报一个未连接的异常,只是不太明白先设置非阻塞再进行主机连接就会有如此恶心人之问题……闲来无事,非常犄角旮旯的问题,如果有知道原理的大大们还望不吝赐教,给大家科普一下啊!小的感激不尽~java

解决方案 »

  1.   

    这个问题很简单啊,如果我没理解错的话,是这样的如果你先设置了非阻塞模式:this.channel.configureBlocking(false);
    那么this.channel.connect(new InetSocketAddress(ip, port));这句就不会阻塞了
    直接执行到你下面写数据,这个时候连接并没有完全创建完成(非阻塞模式)因为SocketChannel默认是阻塞模式的,所以你先调用
    this.channel.connect(new InetSocketAddress(ip, port));
    这个时候,他其实是阻塞了,比如花了1秒,连接完全创建以后才继续执行下面的语句具体你可以实验
    this.channel.configureBlocking(true);
    this.channel.connect(new InetSocketAddress(ip, port));
    这样应该是不会报错了,如果非要先设置false,那就只有sleep到连接完成再写数据具体判断你可以看看java nio P98
    The SocketChannel has been switched back to blocking mode since calling connect( )
    in nonblocking mode. If necessary, the invoking thread blocks until connection
    establishment is complete. finishConnect( ) then returns true.