import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;


public class hello {
public static void main(String args[]) throws Exception
{
Selector selector = Selector.open();

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
InetSocketAddress address = new InetSocketAddress(9000);
serverSocketChannel.socket().bind(address);


SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


while (true){
int selectedNum = selector.select();
System.out.println("Selected Number is :"+selectedNum);
Iterator iter = selector.selectedKeys().iterator();

while(iter.hasNext()){
SelectionKey selectedKey = (SelectionKey)iter.next();

if ((selectedKey.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT){
ServerSocketChannel serverChannel = (ServerSocketChannel)selectedKey.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);

SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);
iter.remove();

//System.out.println("buffer: "+new String(buffer.array()));
}
else if ( (selectedKey.readyOps()&SelectionKey.OP_READ) == SelectionKey.OP_READ ){
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = (SocketChannel)selectedKey.channel();
while (true){
buffer.clear();
int i=socketChannel.read(buffer);

if (i == -1) break;

buffer.flip();
socketChannel.write(buffer);
}
}

}

}


}
}



相关文章:

  • 2021-11-20
  • 2021-04-01
  • 2021-07-08
  • 2021-11-21
  • 2021-09-27
  • 2021-04-16
  • 2021-08-25
  • 2021-07-26
猜你喜欢
  • 2021-12-16
  • 2021-08-30
  • 2021-10-18
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
相关资源
相似解决方案