|Did you know ...||Search Documentation:|
|The stream_pool library|
library(streampool) library dispatches input from
multiple streams based on wait_for_input/3.
It is part of the clib package as it is used most of the time together
library(socket) library. On non-Unix systems it
often can only be used with socket streams.
With SWI-Prolog 5.1.x, multi-threading often provides a good
alternative to using this library. In this schema one thread watches the
listening socket waiting for connections and either creates a thread per
connection or processes the accepted connections with a pool of
worker threads. The library
provides an example realising a mult-threaded HTTP server.
If Goal is called, there is some input on the associated stream. Goal must be careful not to block as this will block the entire pool.1This is hard to achieve at the moment as none of the Prolog read-commands provide for a timeout.
Below is a very simple example that reads the first line of input and echos it back.
:- use_module(library(streampool)). server(Port) :- tcp_socket(Socket), tcp_bind(Socket, Port), tcp_listen(Socket, 5), tcp_open_socket(Socket, In, _Out), add_stream_to_pool(In, accept(Socket)), stream_pool_main_loop. accept(Socket) :- tcp_accept(Socket, Slave, Peer), tcp_open_socket(Slave, In, Out), add_stream_to_pool(In, client(In, Out, Peer)). client(In, Out, _Peer) :- read_line_to_codes(In, Command), close(In), format(Out, 'Please to meet you: ~s~n', [Command]), close(Out), delete_stream_from_pool(In).