集册 Java实例教程 创建新的服务器套接字通道

创建新的服务器套接字通道

欢马劈雪     最近更新时间:2020-01-02 10:19:05

403
创建一个新的服务器套接字通道
/*时代Java - N o w  J a v a . c o m*/

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;


public class Main {

  public static void main(String[] args) {

    final int DEFAULT_PORT = 5555;

    final String IP = "127.0.0.1";

    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

    try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {

      if (serverSocketChannel.isOpen()) {

        serverSocketChannel.configureBlocking(true);

        serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);

        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

        serverSocketChannel.bind(new InetSocketAddress(IP, DEFAULT_PORT));

        System.out.println("Waiting for connections ...");

        while (true) {

          try (SocketChannel socketChannel = serverSocketChannel.accept()) {/* 来自 nowjava*/

            System.out.println("Incoming connection from: "

                + socketChannel.getRemoteAddress());

            while (socketChannel.read(buffer) != -1) {

              buffer.flip();

              socketChannel.write(buffer);

              if (buffer.hasRemaining()) {

                buffer.compact();

              } else {

                buffer.clear();

       
展开阅读全文