/////////////////////////////////// SERVER /////////////////////// import java.util.Map; import java.util.HashMap; import java.util.Date; import java.util.Iterator; import java.nio.channels.ServerSocketChannel; import java.nio.channels.Selector; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.BindException; import java.lang.SecurityException; public class Server implements Runnable { ServerSocketChannel serverSocketChannel; ServerSocket serverSocket; Dispatcher dispatcher; boolean running; public Server() { dispatcher = new Dispatcher(); new Thread(this).start(); } public void run() { try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(true); serverSocket = serverSocketChannel.socket(); serverSocket.bind(new InetSocketAddress(17223)); } catch(BindException e1) { System.out.println("Puerto " + 17223 + " ocupado"); return; } catch(SecurityException e2) { System.out.println("Permisos"); return; } catch(IOException e3) { System.out.println("Imposible iniciar servidor"); if(serverSocket != null) { try { serverSocket.close(); } catch(IOException e4){} } return; } System.out.println("Servidor iniciado, escuchando en puerto : 17223"); running = true; while(running) { SocketChannel socketChannel = null; try { socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); } catch(IOException ioe) { System.out.println("No se obtuvo un nuevo socketChannel"); continue; } InetAddress addr = socketChannel.socket().getInetAddress(); System.out.println("Conexion recibida desde (" + addr.getHostAddress() + ") : " + addr.getHostName()); //se registra el nuevo cliente en el siguiente dispatcher dispatcher.register(socketChannel); } System.out.println("Servidor detenido"); } public void stop() { try { running = false; serverSocket.close(); } catch(IOException e ) { System.out.println("Cerrar serverSocket"); } } public static void main(String[] args) { try { Server server = new Server(); //se iguala a nul algunos parametros para que el Garbage Collector //los libere, ya que son variables que nunca se volverán a ocupar } catch(Exception e) { System.out.println("Excepcion ocurrida en el Main"); System.exit(0); } } } import java.nio.channels.Selector; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.nio.ByteBuffer; import java.io.IOException; import java.util.Iterator; import java.lang.Thread; public class Dispatcher extends Thread { Object guard = new Object(); Selector selector; boolean running; public Dispatcher() { try { this.selector = Selector.open(); this.running = true; start(); } catch(IOException e) { System.out.println("Selector open failed"); } } public void register(SocketChannel socketChannel) { synchronized(guard) { selector.wakeup(); try { socketChannel.register(selector, SelectionKey.OP_READ); } catch(Exception e) { System.out.println("Channel registration failed"); } } } public void run() { running = true; while(running) { synchronized(guard) { // detener el thread del dispatcher si alguien mas esta // accesando al selector (register() method) } try { //Si regresa 0, no hay operaciones de E/S int n = selector.select(); System.out.println("n : " + n); if(n < 1) continue; } catch(IOException e) { System.out.println("selector.select() Error"); continue; } //Un cliente solo puede generar eventos de lectura, es decir, //escritura para el y lectura para el server Iterator it = selector.selectedKeys().iterator(); while(it.hasNext()) { SelectionKey key = it.next(); it.remove(); if(key.isValid() && key.isReadable()) { // se registra la peticion en la cola de peticiones System.out.println("read event valid and readable"); } } } } public void killIt() { running = false; } } //////////////////////////// CLIENT //////////////////////////////// import java.nio.channels.SocketChannel; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.ByteBuffer; import java.net.InetSocketAddress; import java.net.Socket; import java.io.BufferedReader; import java.io.InputStreamReader; public class Connection { public static void main(String[] args) { try { SocketChannel sc = SocketChannel.open(); System.out.println("making conection ..."); sc.socket().connect(new InetSocketAddress("localhost", 17223)); Thread.currentThread().sleep(3000); //Socket socket = new Socket("localhost", 17223); System.out.println("connection established"); BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); //WritableByteChannel output = Channels.newChannel(System.out); ByteBuffer buffer = ByteBuffer.allocate(100); String cad = in.readLine(); while(!"exit".equals(cad.toLowerCase())) { buffer.put(cad.getBytes()); buffer.flip(); sc.write(buffer); buffer.clear(); cad = in.readLine(); } //Thread.currentThread().sleep(3000); sc.close(); sc.socket().close(); //Thread.currentThread().sleep(5000); //socket.close(); } catch(Exception e) { e.printStackTrace(); System.exit(0); } } }