Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. @Override
  2. public void run(){
  3. try{
  4. final Selector channelSelector = Selector.open();
  5. this.serverSocketChannel.register(channelSelector, SelectionKey.OP_ACCEPT);
  6.  
  7. while(this.alive && !this.socketMonitor.isInterrupted()){
  8. channelSelector.selectNow();
  9. Iterator<SelectionKey> iterator = channelSelector.selectedKeys().iterator();
  10. while (iterator.hasNext()) {
  11. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  12. SelectionKey key = iterator.next();
  13. iterator.remove();
  14.  
  15. if(!key.isValid())
  16. continue;
  17.  
  18. if (key.isAcceptable()) {
  19. if(this.actualConnectionHandleds.size() >= this.maxconnections)
  20. key.cancel();
  21. else {
  22.  
  23. try{
  24. // ACCEPT SOCKET
  25. SocketChannel socketChannel = this.serverSocketChannel.accept();
  26. socketChannel.configureBlocking(false);
  27. socketChannel.register(channelSelector, SelectionKey.OP_READ);
  28.  
  29. // REGISTER
  30. NioConnectionHandler connectionHandled = new NioConnectionHandler();
  31. connectionHandled.onConnection(socketChannel);
  32. this.actualConnectionHandleds.put(socketChannel, connectionHandled);
  33. } catch(Exception e){
  34. System.err.println("Can't catch new connection!");
  35. e.printStackTrace();
  36. }
  37. }
  38. } else if(key.isReadable()){
  39. SocketChannel socketChannel = (SocketChannel)key.channel();
  40. NioConnectionHandler connectionHandler = this.actualConnectionHandleds.get(socketChannel);
  41. try{
  42. int len = 0;
  43. if((len = socketChannel.read(byteBuffer)) > -1){
  44. byte[] buffer = new byte[len];
  45. buffer = Arrays.copyOf(byteBuffer.array(), len);
  46.  
  47. connectionHandler.onDataArrival(buffer);
  48. } else {
  49. key.cancel();
  50. connectionHandler.onDissconection(socketChannel);
  51. this.actualConnectionHandleds.remove(socketChannel);
  52. }
  53. } catch(Exception e){
  54. key.cancel();
  55. connectionHandler.onDissconection(socketChannel);
  56. this.actualConnectionHandleds.remove(socketChannel);
  57.  
  58. e.printStackTrace();
  59. }
  60. }
  61. byteBuffer = ByteBuffer.allocate(1024);
  62. }
  63. Thread.sleep(this.elapsedTime);
  64. }
  65. } catch(Exception e){
  66. System.err.println("ERROR: CAN'T MANAGE CONNECTIONS!");
  67. }
  68. }
  69.  
  70. public void stopCatchingConnections() {
  71. try{
  72. this.alive = false;
  73. this.socketMonitor.join();
  74. this.socketMonitor.interrupt();
  75. } catch(Exception e){
  76. e.printStackTrace();
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement