Advertisement
Guest User

Untitled

a guest
Nov 21st, 2018
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.24 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.nio.*;
  4. import java.nio.channels.*;
  5. import java.nio.charset.*;
  6. import java.util.*;
  7.  
  8. public class Server
  9. {
  10.   static private Selector selector;
  11.   // A pre-allocated buffer for the received data
  12.   static private final ByteBuffer buffer = ByteBuffer.allocate( 16384 );
  13.  
  14.   // Decoder for incoming text -- assume UTF-8
  15.   static private final Charset charset = Charset.forName("UTF8");
  16.   static private final CharsetDecoder decoder = charset.newDecoder();
  17.  
  18.  
  19.   static public void main( String args[] ) throws Exception {
  20.     // Parse port from command line
  21.     int port = Integer.parseInt( args[0] );
  22.    
  23.     try {
  24.       // Instead of creating a ServerSocket, create a ServerSocketChannel
  25.       ServerSocketChannel ssc = ServerSocketChannel.open();
  26.  
  27.       // Set it to non-blocking, so we can use select
  28.       ssc.configureBlocking( false );
  29.  
  30.       // Get the Socket connected to this channel, and bind it to the
  31.       // listening port
  32.       ServerSocket ss = ssc.socket();
  33.       InetSocketAddress isa = new InetSocketAddress( port );
  34.       ss.bind( isa );
  35.  
  36.       // Create a new Selector for selecting
  37.       selector = Selector.open();
  38.  
  39.       // Register the ServerSocketChannel, so we can listen for incoming
  40.       // connections
  41.       ssc.register( selector, SelectionKey.OP_ACCEPT );
  42.       System.out.println( "Listening on port "+port );
  43.  
  44.       while (true) {
  45.         // See if we've had any activity -- either an incoming connection,
  46.         // or incoming data on an existing connection
  47.         int num = selector.select();
  48.  
  49.         // If we don't have any activity, loop around and wait again
  50.         if (num == 0) {
  51.           continue;
  52.         }
  53.  
  54.         // Get the keys corresponding to the activity that has been
  55.         // detected, and process them one by one
  56.         Set<SelectionKey> keys = selector.selectedKeys();
  57.         Iterator<SelectionKey> it = keys.iterator();
  58.         while (it.hasNext()) {
  59.           // Get a key representing one of bits of I/O activity
  60.           SelectionKey key = it.next();
  61.  
  62.           // What kind of activity is it?
  63.           if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
  64.             SelectionKey.OP_ACCEPT) {
  65.  
  66.             // It's an incoming connection.  Register this socket with
  67.             // the Selector so we can listen for input on it
  68.             Socket s = ss.accept();
  69.             System.out.println( "Got connection from "+s );
  70.  
  71.             // Make sure to make it non-blocking, so we can use a selector
  72.             // on it.
  73.             SocketChannel sc = s.getChannel();
  74.             sc.configureBlocking( false );
  75.  
  76.             // Register it with the selector, for reading
  77.             sc.register( selector, SelectionKey.OP_READ );
  78.  
  79.           } else if ((key.readyOps() & SelectionKey.OP_READ) ==
  80.             SelectionKey.OP_READ) {
  81.  
  82.             SocketChannel sc = null;
  83.  
  84.             try {
  85.  
  86.               // It's incoming data on a connection -- process it
  87.              
  88.               sc = (SocketChannel)key.channel();
  89.               boolean ok = processInput( sc );
  90.  
  91.               // If the connection is dead, remove it from the selector
  92.               // and close it
  93.               if (!ok) {
  94.                 key.cancel();
  95.  
  96.                 Socket s = null;
  97.                 try {
  98.                   s = sc.socket();
  99.                   System.out.println( "Closing connection to "+s );
  100.                   s.close();
  101.                 } catch( IOException ie ) {
  102.                   System.err.println( "Error closing socket "+s+": "+ie );
  103.                 }
  104.               }
  105.  
  106.             } catch( IOException ie ) {
  107.  
  108.               // On exception, remove this channel from the selector
  109.               key.cancel();
  110.  
  111.               try {
  112.                 sc.close();
  113.               } catch( IOException ie2 ) { System.out.println( ie2 ); }
  114.  
  115.               System.out.println( "Closed "+sc );
  116.             }
  117.           }
  118.         }
  119.  
  120.         // We remove the selected keys, because we've dealt with them.
  121.         keys.clear();
  122.       }
  123.     } catch( IOException ie ) {
  124.       System.err.println( ie );
  125.     }
  126.   }
  127.  
  128.  
  129.   // Just read the message from the socket and send it to stdout
  130.   static private boolean processInput( SocketChannel sc ) throws IOException {
  131.         // Read the message to the buffer
  132.         buffer.clear();
  133.         sc.read( buffer );
  134.         buffer.flip();
  135.  
  136.         // If no data, close the connection
  137.         if (buffer.limit()==0) {
  138.             return false;
  139.         }
  140.  
  141.         // Decode and print the message to stdout
  142.         String message = decoder.decode(buffer).toString();
  143.         System.out.println("RECEIVED: "+ message);
  144.         buffer.flip();
  145.         //InetSocketAddress isa = new InetSocketAddress( port );
  146.         //ss.bind( isa );
  147.  
  148.       // Create a new Selector for selecting
  149.       //selector = Selector.open();
  150.  
  151.         Set<SelectionKey> keys = selector.selectedKeys();
  152.         Iterator<SelectionKey> it = keys.iterator();
  153.         while (it.hasNext()) {
  154.             System.out.println("One for each connect");
  155.             // Get a key representing one of bits of I/O activity
  156.             SelectionKey key = it.next();
  157.             if(key.isAcceptable())
  158.                 continue;
  159.             SocketChannel scAux = (SocketChannel)key.channel();
  160.            
  161.             scAux.write(buffer);
  162.             buffer.rewind();
  163.         }
  164.        
  165.         buffer.clear();
  166.  
  167.         return true;
  168.     }
  169. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement