这种问题通常设置一个标志
boolean b=true;
改为
在之前boolean b=true;
然后
if(key.isWritable()&&b==true) {//如果是通道写准备好事件
System.out.println("writeable");
//取得套接字后处理
Socket socket = (Socket) key.attachment();
SocketChannel channel = (SocketChannel)socket.getChannel();
writeToChannel( channel,"This is from server!");
}
在写数据的过程中
b=false;
boolean b=true;
改为
在之前boolean b=true;
然后
if(key.isWritable()&&b==true) {//如果是通道写准备好事件
System.out.println("writeable");
//取得套接字后处理
Socket socket = (Socket) key.attachment();
SocketChannel channel = (SocketChannel)socket.getChannel();
writeToChannel( channel,"This is from server!");
}
在写数据的过程中
b=false;
打出来看看!!
writeToChannel的作用就是往channel中写数据,具体的源代码晚上才能贴出来,现在在公司,源码在家,呵呵~~~~
public void writeToChannel( SocketChannel channel, String message )
throws IOException {
ByteBuffer buf = ByteBuffer.wrap( message.getBytes() );
int nbytes = channel.write( buf );
}就这么简单,但就这样导至了死循环,呵~~~