Java Tutorial/Network/ServerSocketChannel

Материал из Java эксперт
Перейти к: навигация, поиск

Accepting a Connection on a ServerSocketChannel

import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    int port = 80;
    ssChannel.socket().bind(new InetSocketAddress(port));
    int localPort = ssChannel.socket().getLocalPort();
    SocketChannel sChannel = ssChannel.accept();
    if (sChannel == null) {
    } else {
    }
  }
}





Detecting When a Non-Blocking Socket Is Closed by the Remote Host

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Main {
  public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();
    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));
    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));
    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      selector.select();
      Iterator it = selector.selectedKeys().iterator();
      while (it.hasNext()) {
        SelectionKey selKey = (SelectionKey) it.next();
        it.remove();
        if (selKey.isAcceptable()) {
          ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
          SocketChannel sc = ssChannel.accept();
          ByteBuffer buf = ByteBuffer.allocate(100);
          int numBytesRead = sc.read(buf);
      
          if (numBytesRead == -1) {
              sc.close();
          } else {
              // Read the bytes from the buffer
          }
          int numBytesWritten = sc.write(buf);
        }
      }
    }
  }
}





New IO Hello Server

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class MainClass {
  public final static int PORT = 2345;
  public static void main(String[] args) throws Exception {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    SocketAddress port = new InetSocketAddress(PORT);
    serverChannel.socket().bind(port);
    while (true) {
      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();
    }
  }
}





ServerSocketChannel

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class MainClass {
  private static byte[] data = new byte[255];
  public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
      data[i] = (byte) i;
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      selector.select();
      Set readyKeys = selector.selectedKeys();
      Iterator iterator = readyKeys.iterator();
      while (iterator.hasNext()) {
        SelectionKey key = (SelectionKey) iterator.next();
        iterator.remove();
        if (key.isAcceptable()) {
          SocketChannel client = server.accept();
          System.out.println("Accepted connection from " + client);
          client.configureBlocking(false);
          ByteBuffer source = ByteBuffer.wrap(data);
          SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
          key2.attach(source);
        } else if (key.isWritable()) {
          SocketChannel client = (SocketChannel) key.channel();
          ByteBuffer output = (ByteBuffer) key.attachment();
          if (!output.hasRemaining()) {
            output.rewind();
          }
          client.write(output);
        }
        key.channel().close();
      }
    }
  }
}





Test non-blocking accept() using ServerSocketChannel

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
 * Test non-blocking accept() using ServerSocketChannel.
 */
public class MainClass {
  public static final String GREETING = "Hello I must be going.\r\n";
  public static void main(String[] argv) throws Exception {
    int port = 1234; // default
    ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(port));
    ssc.configureBlocking(false);
    while (true) {
      System.out.println("Waiting for connections");
      SocketChannel sc = ssc.accept();
      if (sc == null) {
        Thread.sleep(2000);
      } else {
        System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
        buffer.rewind();
        sc.write(buffer);
        sc.close();
      }
    }
  }
}





Using a Selector to Manage Non-Blocking Server Sockets

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Main {
  public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();
    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));
    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));
    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      selector.select();
      Iterator it = selector.selectedKeys().iterator();
      while (it.hasNext()) {
        SelectionKey selKey = (SelectionKey) it.next();
        it.remove();
        if (selKey.isAcceptable()) {
          ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
          SocketChannel sc = ssChannel.accept();
          ByteBuffer bb =ByteBuffer.allocate(100);
          sc.read(bb);
          
        }
      }
    }
  }
}