struct_network.sleela
impl/examples/struct_network.sleela · 76 line(s) · sleela
#sleela 2.1
// struct_network.sleela -- structs across the network / control paths.
//
// A struct instance is a VM-local handle, so it cannot be sent over a socket
// directly. structPack(instance) serialises it to a JSON String; the peer
// rebuilds it with structUnpack(TypeName, json). This is the honest transport
// story: the wire carries a self-describing value, not an in-process handle.
struct Order {
String symbol;
int shares;
double limit;
}
class StructNetwork {
// The network worker has no object receiver; shared socket state is static.
static int listener;
static int port;
// listen() returns -1 when the port is taken, so try a small range
// instead of failing when another process holds the first port.
static int openListener() {
int candidate = 45231;
while (candidate < 45263) {
int handle = listen(candidate);
if (handle >= 0) {
port = candidate;
return handle;
}
candidate = candidate + 1;
}
return -1;
}
// Server: accept one client, receive a packed Order, rebuild it, and
// acknowledge with a computed notional value.
static void server() {
int client = accept(listener);
String json = sockread(client);
Order o = structUnpack(Order, json);
double notional = o.shares * o.limit;
sockwrite(client, "ACK " + o.symbol + " x" + o.shares + " notional=" + notional);
sockclose(client);
}
// Client: build an Order, pack it to JSON, send it, and read the ack.
static String client() {
Order o = new Order();
o.symbol = "AAPL";
o.shares = 100;
o.limit = 332.27;
String wire = structPack(o);
print("wire = " + wire);
int socket = connect("127.0.0.1", port);
sockwrite(socket, wire);
String ack = sockread(socket);
sockclose(socket);
return ack;
}
static void main() {
listener = openListener();
if (listener < 0) {
print("struct_network: no free port in 45231-45262");
throw "struct_network: no free port";
}
spawn(server);
String ack = client();
print(ack);
join();
sockclose(listener);
}
}