Std
Socket
Overview
The Socket struct in std::net provides async TCP socket operations built on top of the Djinn runtime's event loop.
import std::net;Constructor
Socket sock = Socket();Creates a new TCP socket. Asserts on failure.
Fields
Field
Type
Description
fdi64File descriptor for the underlying socketconnectedboolWhether the socket is currently connectedMethods
Method
Description
bind(i8* addr, i32 port) → i64Binds the socket to an address and port.listen(i32 backlog) → i64Starts listening for incoming connections.await accept() → SocketAsync. Accepts an incoming connection, returns a new Socket.await connect(i8* addr, i32 port) → i64Async. Connects to a remote address.await send(void* buf, i64 count) → i64Async. Sends data. Asserts if not connected.await recv(void* buf, i64 count) → i64Async. Receives data. Sets connected=false on disconnect.isConnected() → boolReturns whether the socket is connected.close() → i64Closes the socket.Server Example
import std::net;
import std::sys;
async void main() {
Socket server = Socket();
server.bind("0.0.0.0", 8080);
server.listen(128);
while (true) {
Socket client = await server.accept();
i8* buf = i8[1024];
i64 n = await client.recv(buf, 1024);
await client.send(buf, n); // echo back
client.close();
}
}Client Example
import std::net;
async void main() {
Socket sock = Socket();
await sock.connect("127.0.0.1", 8080);
i8* msg = "Hello, server!";
await sock.send(msg, 14);
i8* buf = i8[1024];
i64 n = await sock.recv(buf, 1024);
sock.close();
}