Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Override
- public void run(){
- try{
- final Selector channelSelector = Selector.open();
- this.serverSocketChannel.register(channelSelector, SelectionKey.OP_ACCEPT);
- while(this.alive && !this.socketMonitor.isInterrupted()){
- channelSelector.selectNow();
- Iterator<SelectionKey> iterator = channelSelector.selectedKeys().iterator();
- while (iterator.hasNext()) {
- ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
- SelectionKey key = iterator.next();
- iterator.remove();
- if(!key.isValid())
- continue;
- if (key.isAcceptable()) {
- if(this.actualConnectionHandleds.size() >= this.maxconnections)
- key.cancel();
- else {
- try{
- // ACCEPT SOCKET
- SocketChannel socketChannel = this.serverSocketChannel.accept();
- socketChannel.configureBlocking(false);
- socketChannel.register(channelSelector, SelectionKey.OP_READ);
- // REGISTER
- NioConnectionHandler connectionHandled = new NioConnectionHandler();
- connectionHandled.onConnection(socketChannel);
- this.actualConnectionHandleds.put(socketChannel, connectionHandled);
- } catch(Exception e){
- System.err.println("Can't catch new connection!");
- e.printStackTrace();
- }
- }
- } else if(key.isReadable()){
- SocketChannel socketChannel = (SocketChannel)key.channel();
- NioConnectionHandler connectionHandler = this.actualConnectionHandleds.get(socketChannel);
- try{
- int len = 0;
- if((len = socketChannel.read(byteBuffer)) > -1){
- byte[] buffer = new byte[len];
- buffer = Arrays.copyOf(byteBuffer.array(), len);
- connectionHandler.onDataArrival(buffer);
- } else {
- key.cancel();
- connectionHandler.onDissconection(socketChannel);
- this.actualConnectionHandleds.remove(socketChannel);
- }
- } catch(Exception e){
- key.cancel();
- connectionHandler.onDissconection(socketChannel);
- this.actualConnectionHandleds.remove(socketChannel);
- e.printStackTrace();
- }
- }
- byteBuffer = ByteBuffer.allocate(1024);
- }
- Thread.sleep(this.elapsedTime);
- }
- } catch(Exception e){
- System.err.println("ERROR: CAN'T MANAGE CONNECTIONS!");
- }
- }
- public void stopCatchingConnections() {
- try{
- this.alive = false;
- this.socketMonitor.join();
- this.socketMonitor.interrupt();
- } catch(Exception e){
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement