FileDocCategorySizeDatePackage
NewIOHelloServer.javaAPI DocExample1311Tue Feb 14 06:30:36 GMT 2006None

NewIOHelloServer

public class NewIOHelloServer extends Object

Fields Summary
public static final int
PORT
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


         
    
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    SocketAddress port = new InetSocketAddress(PORT);
    serverChannel.socket().bind(port);
    
    while (true) {
      try {
        SocketChannel clientChannel = serverChannel.accept();
          
        String response = "Hello " 
         + clientChannel.socket().getInetAddress() + " on port " 
         + clientChannel.socket().getPort() + "\r\n";
        response += "This is " + serverChannel.socket() + " on port " 
         + serverChannel.socket().getLocalPort() + "\r\n";
        
        byte[] data = response.getBytes("UTF-8");
        ByteBuffer buffer = ByteBuffer.wrap(data);
        while (buffer.hasRemaining()) clientChannel.write(buffer);
        clientChannel.close();
      }
      catch (IOException ex) {
        // This is an error on one connection. Maybe the client crashed.
        // Maybe it broke the connection prematurely. Whatever happened, 
        // it's not worth shutting down the server for. 
      }
    }  // end while