问题描述:

服务端已启动,端口9999。

客户端通过Channel方式实现,功能一切正常。

客户端通过Selector+Channel方式实现,程序报错。

哪位兄台遇到过此问题,请赐教

Exception in thread "main" java.nio.channels.NotYetConnectedException

at sun.nio.ch.SocketChannelImpl.ensureWriteOpen(SocketChannelImpl.java:269)

at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:474)

at demo.nio.SelectorDemo.run(SelectorDemo.java:55)

at demo.nio.SelectorDemo.main(SelectorDemo.java:24)

服务端代码:

package demo.nio;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

/**

* @ClassName: ServerSocketChannel

* @Description:

* @author

* @date 2018年1月24日 下午9:53:15

*

*/

public class ServerSocketChannelDemo implements Runnable {

public static void main(String[] args) {

ServerSocketChannelDemo serverSocketChannelDemo = new ServerSocketChannelDemo();

serverSocketChannelDemo.run();

}

public void run() {

try {

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(9999));

serverSocketChannel.configureBlocking(false);

while(true){

SocketChannel socketChannel = serverSocketChannel.accept();

if(socketChannel != null){

//do something with socketChannel...

ByteBuffer buf1 = ByteBuffer.allocate(10000);

socketChannel.read(buf1);

buf1.flip();

if(buf1.hasRemaining())

System.out.println(">>>服务端收到数据:"+new String(buf1.array()));

buf1.clear();

ByteBuffer buf2 = ByteBuffer.allocate(10000);

buf2.put("A word from server!".getBytes());

buf2.flip();

socketChannel.write(buf2);

socketChannel.close();

}else{

Thread.sleep(3000);

}

}

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

客户端代码(Channel实现):

package demo.nio;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

/**

* @ClassName: SocketChannelDemo

* @Description:

* @author

* @date 2018年1月11日 下午10:01:40

*

*/

public class SocketChannelDemo implements Runnable{

public static void main(String[] args) {

SocketChannelDemo socketChannelDemo = new SocketChannelDemo();

socketChannelDemo.run();

}

public void run() {

try {

//通道

SocketChannel socketChannel = SocketChannel.open();

socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

while(!socketChannel.finishConnect()){

wait(1000);

}

//缓冲区

ByteBuffer buf1 = ByteBuffer.allocate(10000);

buf1.put("A word from client!".getBytes());

buf1.flip();

if(buf1.hasRemaining())

socketChannel.write(buf1);

buf1.clear();

ByteBuffer buf2 = ByteBuffer.allocate(10000);

socketChannel.read(buf2);

if(buf2.hasRemaining())

System.out.println(">>>客户端接收数据:"+new String(buf2.array()));

buf2.clear();

socketChannel.close();

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

客户端代码(Selector+Channel实现):

package demo.nio;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectableChannel;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Set;

import java.util.Iterator;

/**

* @ClassName: SelectorDemo

* @Description:

* @author

* @date 2018年1月12日 下午9:06:21

*

*/

public class SelectorDemo implements Runnable{

public static void main(String[] args) {

SelectorDemo selectorDemo = new SelectorDemo();

selectorDemo.run();

}

public void run() {

try {

//选择器

Selector selector = Selector.open();

//通道

SocketChannel socketChannel1 = SocketChannel.open();

socketChannel1.configureBlocking(false);

SelectionKey key1 = socketChannel1.register(selector, SelectionKey.OP_CONNECT);

socketChannel1.connect(new InetSocketAddress("127.0.0.1", 9999));

while(true){

int readyChannels = selector.selectNow();//selectNow()非阻塞,select(timeout)和select()阻塞

if(readyChannels == 0)

continue;

//selector.wakeup();//第一个线程调用select后,需要执行此方法,阻塞在select上的线程会立马返回。

Set> selectedKeys = selector.selectedKeys();

Iterator> keyIterator = selectedKeys.iterator();

while(keyIterator.hasNext()){

SelectionKey key = (SelectionKey) keyIterator.next();

if(key.isAcceptable()){

// a connection was accepted by a ServerSocketChannel.

ServerSocketChannel socketchannel = (ServerSocketChannel) key.channel();

}else if(key.isConnectable()){

// a connection was established with a remote server.

SocketChannel socketchannel = (SocketChannel) key.channel();

ByteBuffer buf1 = ByteBuffer.allocate(10000);

buf1.put("A word from client!".getBytes());

buf1.flip();

socketchannel.write(buf1);

buf1.clear();

ByteBuffer buf2 = ByteBuffer.allocate(10000);

socketchannel.read(buf2);

buf2.flip();

System.out.println(">>>客户端接收数据:"+new String(buf2.array()));

buf2.clear();

}else if(key.isReadable()){

// a channel is ready for reading.

SelectableChannel fileChannel = key.channel();

}else if(key.isWritable()){

// a channel is ready for writing.

SelectableChannel fileChannel = key.channel();

}

keyIterator.remove();

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

java channels_java.nio.channels.NotYetConnectedException相关推荐

  1. sparkStreaming+kafka SparkException: java.nio.channels.ClosedChannelException异常报错

    在运行sparkStreaming+kafka的时候报错 java io报错, 如果broker-list的端口不对或者kafka服务端未启动,会遇到以下错误: Exception in thread ...

  2. 【Hadoop】java.io.IOException: Failed on local exception: java.nio.channels.ClosedByInterruptException

    查看日志中的报错信息如下: java.io.IOException: Failed on local exception: java.nio.channels.ClosedByInterruptExc ...

  3. java.nio.channels.UnresolvedAddressException

    RocketMq和Redis的netty版本冲突 报错信息如下 排查原因 解决办法 分析 报错信息如下 java.nio.channels.UnresolvedAddressException - U ...

  4. java.nio.channels.UnresolvedAddressException: null [运行storm-0.9.4集群时]

    [问题描述] 在运行storm集群时,发现kafkaspout不能消费kafka的数据,查看stormUI,没有发现有什么异常,但是手动消费kafka的数据又是正确的,通过一步一步问题排查,最好定位到 ...

  5. Spark2 Failed to send RPC 5346982634 to /ns1:58312: java.nio.channels.ClosedChannelException

    将spark任务运行与yarn上出现以下错误: scala> 18/11/21 16:20:11 ERROR cluster.YarnClientSchedulerBackend: Yarn a ...

  6. 理解Java的NIO

    同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...

  7. java io nio socket_通过socket编程掌握IO流 —— NIO

    一.本次目标 改造server,采用NIO读取client信息: 改造client,亦采用NIO发送消息,与之前不同的BIO形成对比: 二.编码 1.新建byte数组拼接公共类 主要用作在channe ...

  8. java 基础--NIO(4)

          Java    NIO   1.     Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java IO   API NIO与原来的I ...

  9. channels java_Java NIO channels

    Java NIO channels Java 中的channel和流有如下的区别 既可以从通道中读取数据,又可以写数据到通道.但流的读写通常是单向的. 通道可以异步地读写. 通道中的数据总是要先读到一 ...

  10. java BIO NIO AIO 理论篇

    http://furturestrategist.iteye.com/blog/1463369 java中的IO主要源自于网络和本地文件 IO的方式通常分为几种,同步阻塞的BIO.同步非阻塞的NIO. ...

最新文章

  1. 对于大数据大流量情况下微软架构的水平扩展的遐想(瞎想)
  2. php rsa数字签名为空,如何使用PHP将数字签名(RSA,证书等)添加到任何文件?
  3. SGDRegressor
  4. 产品所有者也应该是Scrum教练吗?
  5. Hadoop报错AccessControlException: Permission denied: user=vincent, access=WRITE, inode=/:iie4bu:supe
  6. Unity3D游戏内存瘦身指南: UI优化是关键
  7. Ceph保证数据安全的机制
  8. DTMF采用RFC2833进行带内传输的实现[ZT]
  9. Lync Server 2010 权限相关
  10. GIT提交(COMMIT)代码时,不显示新建的文件
  11. (23)Linux下Clion中搭建opencv环境
  12. 什么是webpack? ----(webpack入门)
  13. app开发人员配置【职责】
  14. c语言之sizeof与strlen全
  15. [转]94个比付费软件更好的免费软件
  16. 简单的程序诠释C++ STL算法系列之八:mismatch
  17. (项目)审计系统(堡垒机)
  18. springboot 启动 ApplicationContext applicationContext = null
  19. 认证 (authentication) 和授权 (authorization)小记
  20. linux下部署服务,启动时显示socket注册失败。数据库连接失败。求帮下忙。

热门文章

  1. 数据库中delete和drop的区别
  2. MindManager2018,修改下载时间
  3. Android WebView 调用相机、相册,压缩图片后上传
  4. fd开发website小技巧
  5. redis(千帆竞发--分布式锁)
  6. 计算机用户密码怎么查看,电脑密码如何查看? 电脑教程:查看方法
  7. vscode中输入感叹号无法识别html模板
  8. 植物大战僵尸开发公司创始人自述:从0到1亿
  9. wpf/sl下的复合程序-CAG入门
  10. 谈谈我是如何选择VC界面皮肤库