51,396
社区成员




package Server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
public class SeverChannel {
public static void main(String[] args) {
// TODO Auto-generated method stub
Start();
}
public static void Start() {
ServerSocketChannel ssc=null;
Selector s=null;
try {
ssc=ServerSocketChannel.open();
s=Selector.open();
ssc.socket().bind(new InetSocketAddress(10086));
ssc.configureBlocking(false);
System.out.println(SelectionKey.OP_ACCEPT|SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
ssc.register(s,SelectionKey.OP_ACCEPT|SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
while(true) {
if(s.select()==0)
{continue;}
Iterator<SelectionKey> keys=s.selectedKeys().iterator();
while(keys.hasNext()) {
SelectionKey key=keys.next();
if(key.isAcceptable())
System.out.println("Accept");
if(key.isConnectable())
System.out.println("Connect");
if(key.isWritable())
System.out.println("Write");
if(key.isReadable())
System.out.println("Read");
keys.remove();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
ssc.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}