Java/Network Protocol/NIO Socket

Материал из Java эксперт
Версия от 07:20, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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 {
    }
  }
}





Creating a Non-Blocking Server Socket

 
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
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));
  }
}





Creating a Non-Blocking Socket: requires a socket channel.

 
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    sChannel.connect(new InetSocketAddress("hostName", 12345));
    while (!sChannel.finishConnect()) {
      // Do something else
    }
  }
}





Finger Server

  
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NewFingerServer {
  private static void readPlan(String userName, PrintWriter pw) throws Exception {
    FileReader file = new FileReader(userName + ".plan");
    BufferedReader buff = new BufferedReader(file);
    boolean eof = false;
    pw.println("\nUser name: " + userName + "\n");
    while (!eof) {
      String line = buff.readLine();
      if (line == null)
        eof = true;
      else
        pw.println(line);
    }
    buff.close();
  }
  public static void main(String[] arguments) throws Exception {
    ServerSocketChannel sockChannel = ServerSocketChannel.open();
    sockChannel.configureBlocking(false);
    InetSocketAddress server = new InetSocketAddress("localhost", 79);
    ServerSocket socket = sockChannel.socket();
    socket.bind(server);
    Selector selector = Selector.open();
    sockChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      selector.select();
      Set keys = selector.selectedKeys();
      Iterator it = keys.iterator();
      while (it.hasNext()) {
        SelectionKey selKey = (SelectionKey) it.next();
        it.remove();
        if (selKey.isAcceptable()) {
          ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
          ServerSocket selSocket = selChannel.socket();
          Socket connection = selSocket.accept();
          
          InputStreamReader isr = new InputStreamReader(connection.getInputStream());
          BufferedReader is = new BufferedReader(isr);
          PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
          pw.println("NIO Finger Server");
          pw.flush();
          String outLine = null;
          String inLine = is.readLine();
          if (inLine.length() > 0) {
            outLine = inLine;
          }
          readPlan(outLine, pw);
          pw.flush();
          pw.close();
          is.close();
          
          connection.close();
        }
      }
    }
  }
}





Non block server

 
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;
import java.util.Set;
public class MainClass {
  public static void main(String[] args) throws IOException {
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();
    ByteBuffer buffer = ByteBuffer.allocate(512);
    Selector selector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));
    server.configureBlocking(false);
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);
    for (;;) {
      selector.select();
      Set keys = selector.selectedKeys();
      for (Iterator i = keys.iterator(); i.hasNext();) {
        SelectionKey key = (SelectionKey) i.next();
        i.remove();
        if (key == serverkey) {
          if (key.isAcceptable()) {
            SocketChannel client = server.accept();
            client.configureBlocking(false);
            SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
            clientkey.attach(new Integer(0));
          }
        } else {
          SocketChannel client = (SocketChannel) key.channel();
          if (!key.isReadable())
            continue;
          int bytesread = client.read(buffer);
          if (bytesread == -1) {
            key.cancel();
            client.close();
            continue;
          }
          buffer.flip();
          String request = decoder.decode(buffer).toString();
          buffer.clear();
          if (request.trim().equals("quit")) {
            client.write(encoder.encode(CharBuffer.wrap("Bye.")));
            key.cancel();
            client.close();
          } else {
            int num = ((Integer) key.attachment()).intValue();
            String response = num + ": " + request.toUpperCase();
            client.write(encoder.encode(CharBuffer.wrap(response)));
            key.attach(new Integer(num + 1));
          }
        }
      }
    }
  }
}





Reading from a SocketChannel

 
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    sChannel.connect(new InetSocketAddress("hostName", 12345));
    int numBytesRead = sChannel.read(buf);
    if (numBytesRead == -1) {
      sChannel.close();
    } else {
      buf.flip();
    }
  }
}





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);
          
        }
      }
    }
  }
}





Writing to a SocketChannel

 
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    sChannel.connect(new InetSocketAddress("hostName", 12345));
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    buf.put((byte) 0xFF);
    buf.flip();
    int numBytesWritten = sChannel.write(buf);
  }
}