
# vsock

> Byte streams between host and guest, with no network in between.

```js
const listener = vm.vsock.listen(5000); // guest programs connect to CID 2, port 5000
vm.write("echo hello | kwbox vsock connect 5000\n");
const conn = await listener.accept();
console.log(await new Response(conn.readable).text()); // "hello\n"
conn.close();

const c = await vm.vsock.connect(6000); // a guest program listening on port 6000
await c.writable.getWriter().write("ping");
```

These are byte streams with real flow control. vsock is on unless you pass `vsock: false`.

## Reach guest servers

```js
const sock = await vm.connect(8000); // TCP to the guest's 127.0.0.1:8000
await new Response("hello\n").body.pipeTo(sock.writable); // then EOF (a half-close)
console.log(await new Response(sock.readable).text());
```

`vm.connect(port)` reaches a TCP server on the guest's loopback through the guest's kwtty, over vsock, so it needs no network. It resolves once the guest has connected (`PtyError` `ECONNREFUSED` if nothing listens) with `readable` and `writable` byte streams, half-close included, `close()` and `closed`. The CLI's `--forward HOSTPORT:GUESTPORT` uses it.

```js
const res = await vm.fetch("http://localhost:8000/");
console.log(await res.text());
```

`vm.fetch(url, init)` sends an HTTP/1.1 request to a server in the guest and returns a `Response` whose body streams. It always connects to the guest's 127.0.0.1 at the URL's port; the host name only goes into the `Host` header, so `vm.fetch("http://localhost:8000/")` reaches a dev server listening on port 8000. `fetchOver(connect, url, init)` is the same client over any byte stream.
