Пример #1
0
  /**
   * Opens a server TCP connection to clients. Creates, binds, and listens
   *
   * @param port local TCP port to listen on
   * @param backlog listen backlog.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int openServer(int port, int backlog) throws IOException {
    int fd = -1;

    fd = sockets.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (DEBUG) {
      System.err.println("Socket.socket() = " + fd);
    }
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

    set_blocking_flags(fd, /*is_blocking*/ false);

    setSockOpt(fd, Socket.SO_REUSEADDR, 1);

    setSockOpt(fd, Socket.IPPROTO_TCP, Socket.TCP_NODELAY, 1);

    Socket.sockaddr_in local_sin = new Socket.sockaddr_in();
    local_sin.sin_family = Socket.AF_INET;
    local_sin.sin_port = Inet.htons((short) port);
    local_sin.sin_addr = Socket.INADDR_ANY;
    if (DEBUG) {
      System.err.println("Socket.bind(" + fd + ", " + local_sin + ")");
    }

    if (sockets.bind(fd, local_sin, local_sin.size()) < 0) {
      throw newError(fd, "bind");
    }

    if (sockets.listen(fd, backlog) < 0) {
      throw newError(fd, "listen");
    }

    return fd;
  }