예제 #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 = Socket.INSTANCE.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

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

    IntByReference option_val = new IntByReference(1);
    if (sockets.setsockopt(fd, Socket.SOL_SOCKET, Socket.SO_REUSEADDR, option_val, 4) < 0) {
      throw newError(fd, "setSockOpt");
    }
    option_val.free();

    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 (sockets.bind(fd, local_sin) < 0) {
      throw newError(fd, "bind");
    }

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

    return fd;
  }