public class TestNonBlockingNIO {
@Test
public void client() throws IOException
{
SocketChannel sChannel
= SocketChannel
.open(new InetSocketAddress("127.0.0.1", 9898));
sChannel
.configureBlocking(false);
ByteBuffer buf
= ByteBuffer
.allocate(1024);
Scanner scanner
= new Scanner(System
.in
);
while(scanner
.hasNext()){
String str
= scanner
.next();
buf
.put((new Date().toString() + "\n" + str
).getBytes());
buf
.flip();
sChannel
.write(buf
);
buf
.clear();
}
sChannel
.close();
}
@Test
public void server() throws IOException
{
ServerSocketChannel ssChannel
= ServerSocketChannel
.open();
ssChannel
.configureBlocking(false);
ssChannel
.bind(new InetSocketAddress(9898));
Selector selector
= Selector
.open();
ssChannel
.register(selector
, SelectionKey
.OP_ACCEPT
);
while(selector
.select() > 0){
Iterator
<SelectionKey> it
= selector
.selectedKeys().iterator();
while(it
.hasNext()){
SelectionKey sk
= it
.next();
if(sk
.isAcceptable()){
SocketChannel sChannel
= ssChannel
.accept();
sChannel
.configureBlocking(false);
sChannel
.register(selector
, SelectionKey
.OP_READ
);
}else if(sk
.isReadable()){
SocketChannel sChannel
= (SocketChannel
) sk
.channel();
ByteBuffer buf1
= ByteBuffer
.allocate(1024);
int len
= 0;
while((len
= sChannel
.read(buf1
)) > 0 ){
buf1
.flip();
System
.out
.println(new String(buf1
.array(), 0, len
));
buf1
.clear();
}
}
it
.remove();
}
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-3124.html