Add tcp module

This commit is contained in:
Alexander Heldt
2025-11-09 21:29:59 +01:00
parent 8bbfae4592
commit 77f441dea4
3 changed files with 305 additions and 0 deletions

57
src/tcp/tcp.gleam Normal file
View File

@@ -0,0 +1,57 @@
import gleam/bytes_tree
import tcp/reason.{type Reason}
pub type Socket
// https://www.erlang.org/doc/apps/kernel/inet#t:address_family/0
// local socket
type Local {
Local(socket_path: String)
}
type ModeValue {
Binary
}
type TCPOption {
Active(Bool)
Mode(ModeValue)
}
pub fn connect(socket_path: String) -> Result(Socket, Reason) {
let options = [Mode(Binary), Active(False)]
// timeout in ms
let timeout = 1000
gen_tcp_connect(Local(socket_path), 0, options, timeout)
}
pub fn send(socket: Socket, message: String) -> Result(Nil, Reason) {
gen_tcp_send(socket, bytes_tree.from_string(message))
}
pub fn close(socket: Socket) -> Nil {
gen_tcp_close(socket)
}
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#connect/4
@external(erlang, "gen_tcp", "connect")
fn gen_tcp_connect(
address: Local,
port: Int,
options: List(TCPOption),
timeout: Int,
) -> Result(Socket, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#send/2
@external(erlang, "tcp_ffi", "send")
fn gen_tcp_send(
socket: Socket,
packet: bytes_tree.BytesTree,
) -> Result(Nil, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#close/1
@external(erlang, "gen_tcp", "close")
fn gen_tcp_close(socket: Socket) -> Nil