cleaned up the set of samples
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
# Implementation of a basic TCP server that listen for connections and prints received bytes.
|
||||
|
||||
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, ': ', data, '\n');
|
||||
}
|
||||
|
||||
fun on_disconnect(addr)
|
||||
{
|
||||
print(addr, ' disconnected.\n');
|
||||
}
|
||||
|
||||
startServer({on_connect: on_connect, on_datain: on_datain, on_disconnect: on_disconnect}, 8080);
|
||||
Reference in New Issue
Block a user