# `hopen`, `hclose`


[`hopen`](#hopen)   connect a process or file
[`hclose`](#hclose)  disconnect a process or file


KDB-X communicates with the [file system](files.md) and other processes in two ways:

- One-shot functions
- [Handles](handles.md) to persistent connections

`hopen` opens connections and `hclose` closes them.

## `hopen`

_Open a connection to a file or process_
```syntax
hopen filehandle
hopen processhandle
hopen (communicationhandle;timeout)
hopen port
```

Where

- `filehandle` is a symbol atom or string
- `communicationhandle` is a symbol atom or string
- `timeout` is a number of milliseconds as a long atom
- `port` is a local port number as a long atom

connects to a file object or a communication handle, and returns a connection handle as an int.
```q
hopen ":path/to/file.txt"                   / filehandle
hopen `:unix://5010                         / localhost, Unix domain socket
hopen `:tcps://mydb.us.com:5010             / SSL/TLS with hostname
hopen(":10.43.23.198:5010";10000)           / IP address and timeout
hopen 5010                                  / local port number
```

The timeout and the port number must be longs: `hopen 5010i` signals a `'type` error.

For interprocess communication (IPC) compatibility, `hopen` serializes as the lambda `{hopen x}`. It accepts any of these arguments:
```q
hopen each(`:mysymbol;
        ":mycharvector";
        `:localhost:5000;
        ":localhost:5000";
        (`:localhost:5000;1000);
        (":localhost:5000";1000))
```

### Files

If `filehandle` specifies a file path that doesn’t exist, `hopen` creates it, including any directories.
```q
q)hdat:hopen ":sub/dir/f.dat"     / data file (bytes)
q)htxt:hopen ":test.txt"          / text file
```

> **Tip — Passing strings instead of symbols avoids interning them.**
>
>
> This is useful when you embed frequently changing tokens in the username or password fields.
>
> **Warning — Do not use colons in a file path. It conflicts with the pattern used to identify a process.**
>
>
To append to these files, apply the handle to the data, as you do for IPC:
```q
q)r:hdat 0x2324
q)r:htxt "some text\n"
q)r:htxt ` sv("asdf";"qwer")
q)hclose each (hdat;htxt);
q)read1`:sub/dir/f.dat
0x2324
q)read0`:test.txt
"some text"
"asdf"
"qwer"
```

### Processes

#### Communication handles

A communication handle specifies a network resource, and can include authentication credentials for it. There are four forms.

TCP
: `` `:host:port[:user:password]``
: `host` can be a hostname or IP address; if omitted, it defaults to localhost

Unix domain socket
: `` `:unix://port[:user:password] ``
: Unix domain sockets can have significantly lower latency and higher throughput than a localhost TCP connection

SSL/TLS
: `` `:tcps://host:port[:user:password] ``
: TCP with SSL/TLS encryption
: `` `:unixs://port ``
: Unix domain socket with SSL/TLS encryption
: See [SSL/TLS](../how_to/io_and_communication/ssl.md).

FIFO/named pipe
: `` `:fifo://filename``
: Unix only
```q
hopen `:10.43.23.198:5010                    / IP address
hopen ":mydb.us.com:5010"                    / hostname
hopen `::5010                                / localhost
hopen 5010                                   / localhost
hopen `:unix://5010                          / localhost, Unix domain socket
hopen `:tcps://mydb.us.com:5010              / SSL/TLS with hostname
hopen (`:mydb.us.com:5010:elmo:sesame;10000) / full arg list, 10s timeout
```

If the server session was started with the [`-u`](cmdline.md#-u-usr-pwd-local) or [`-U`](cmdline.md#-u-usr-pwd) command-line option, you must supply a user and password. The server passes them to [`.z.pw`](dotz.md#zpw-validate-user) for optional additional processing.

The optional timeout applies to the initial connection, not subsequent use of it.

To send messages to the remote process:
```q
h"2+2"          / synchronous (GET), returns 4
(neg h)"a:2"    / asynchronous (SET)
```

> **Tip — To send HTTP or HTTPS requests, for example to REST APIs and cloud services, use the [Kurl module](../modules/kurl/introduction.md).**
>
>
#### One-shot request

To run only one synchronous query, use a one-shot request: it connects, sends the query, gets the result, then disconnects.
```q
`:mydb.us.com:5010:elmo:sesame "1+1"
```

It is more efficient to keep a connection open if you can reuse it for other queries.

To set a timeout for a one-shot query, use `` `::[(":host:port";timeout);query]``:
```q
`::[(":localhost:5000:username:password";5000);"2+3"]
```

`":host:port"` can also be a symbol as `` `:host:port``.

## `hclose`

_Close a connection to a file or process_
```syntax
hclose x     hclose[x]
```

Where `x` is a connection handle, closes the connection and destroys the handle.
You can no longer apply the corresponding integer to an argument: doing so signals an error such as `'Cannot write to handle 3. OS reports: Bad file descriptor`.
```q
q)h:hopen ":test.txt"
q)h "first line\n";
q)hclose h
q)@[h;"second line\n";{"error: handle is closed"}]
"error: handle is closed"
```

When you close an asynchronous connection, `hclose` doesn't send pending data on the connection handle.
If you need the data sent, flush the handle explicitly before closing it:
```q
neg[h][];hclose h;
```

----

[`.Q.Xf`](dotq.md#xf-create-file) (create file)


[Communication handle](glossary.md#communication-handle),
[Connection handle](glossary.md#connection-handle),
[File system](files.md),
[Interprocess communication](../how_to/io_and_communication/basics.md)


[SSL/TLS](../how_to/io_and_communication/ssl.md),
[Kurl module](../modules/kurl/introduction.md)


_Q for Mortals_
[§11.8.2 Opening a Connection Handle](../learn/q4m/11_IO.md#1182-opening-a-connection-handle)
