Files
Noja/samples/server2.noja
T

107 lines
1.8 KiB
Plaintext

fun startServer(callbacks, port, backlog)
{
# Handle default arguments.
{
if callbacks == none:
callbacks = {};
if port == none:
port = 8000;
if backlog == none:
backlog = 5;
}
fd = net.socket(net.AF_INET, net.SOCK_STREAM, 0);
if fd < 0:
{
print('Failed to create socket.\n');
return none;
}
if net.bind(fd, {
sin_family: net.AF_INET,
sin_port: net.htons(port),
sin_addr: {
s_addr: net.htonl(net.INADDR_ANY)
}
}) != 0:
{
print('Failed to bind.\n');
return none;
}
if net.listen(fd, backlog) != 0:
{
print('Failed to listen.\n');
return none;
}
{
on_datain = callbacks.on_datain;
on_connect = callbacks.on_connect;
on_disconnect = callbacks.on_disconnect;
if on_datain == none:
fun on_datain()
none;
if on_connect == none:
fun on_connect()
none;
if on_disconnect == none:
fun on_disconnect()
none;
}
buffer = newBuffer(1024);
while true:
{
client_addr = {};
client_fd = net.accept(fd, client_addr);
if client_fd < 0:
{
print('Warning! Failed to accept!\n');
continue;
}
addr_str = net.inet_ntoa(client_addr.sin_addr);
on_connect(addr_str);
do
{
n = net.recv(client_fd, buffer, 0);
if n < 0:
print('Warning! Failed to read from socket!\n');
else if n == 0:
on_disconnect(addr_str);
else
on_datain(addr_str, sliceBuffer(buffer, 0, n));
}
while n > 0;
}
}
fun on_connect(addr)
{
print(addr, ' connected.\n');
}
fun on_datain(addr, data)
{
print('Received ', count(data), ' bytes from ', addr, '\n');
}
fun on_disconnect(addr)
{
print(addr, ' disconnected.\n');
}
startServer({on_connect: on_connect, on_datain: on_datain, on_disconnect: on_disconnect}, 8080);