1.NIO例子
public static void main(String[] args) throws IOException {
LinkedList<SocketChannel> clients = new LinkedList();
ServerSocketChannel ss = ServerSocketChannel.open();
ss.bind(new InetSocketAddress(9090));
ss.configureBlocking(false);//非阻塞
while(true){
SocketChannel client = ss.accept();
if(client == null){
// System.out.println("sssaasassaa");
}else{
client.configureBlocking(false);
int port = client.socket().getPort();
System.out.println("client port" + port);
clients.add(client);
}
ByteBuffer buffer = ByteBuffer.allocate(4096);
for(SocketChannel c: clients){
int num = c.read(buffer);
if(num > 0){
buffer.flip();
byte[] aaa = new byte[buffer.limit()];
buffer.get(aaa);
String b = new String(aaa);
System.out.println(c.socket().getPort() + ":" + b);
buffer.clear();
}
}
}
}