Server 端:
package NIO;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class Server {
public static void main(String[] args) throws Exception{
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){
System.out.println("asking beginning :");
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()){
SelectionKey sk = it.next();
if (sk.isAcceptable()){
SocketChannel acChannel = ssChannel.accept();
acChannel.configureBlocking(false);
acChannel.register(selector,SelectionKey.OP_READ);
}
if (sk.isReadable()){
SocketChannel acChannel = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len=0;
while ((len = acChannel.read(buffer))!=0){
buffer.flip();
System.out.println(new String(buffer.array(),0,buffer.limit()));
buffer.clear();
}
}
it.remove();
}
}
}
}
Clint 端:
package NIO;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class Clint {
public static void main(String[] args) throws Exception{
SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
sc.configureBlocking(false);
Scanner scanner = new Scanner(System.in);
ByteBuffer buff = ByteBuffer.allocate(1024);
while (true){
String s = scanner.nextLine();
buff.put(s.getBytes());
buff.flip();
sc.write(buff);
buff.clear();
}
}
}