Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- :-dynamic(wotp_server_port/1).
- wotp_server_port(16996).
- wotp_lambda([Data],Call,Data):-Call.
- % Redirect output stream and read_line_to_string to write to a predicate
- with_output_to_pred(Pred, Call):-
- with_output_to_pred(read_line_to_string, Pred, Call).
- % Redirect output stream to write to a predicate with ReaderPred line [read_line_to_string,get_char,..]
- with_output_to_pred(ReaderPred, Pred, Call):- thread_self(ID),
- wotp_client(ReaderPred, wotp_lambda([Data],thread_signal(ID,call(Pred,Data))),Call).
- wotp_client(ReaderPred,Pred, Call):-
- wotp_create_server,
- must(wotp_server_port(Port)),
- tcp_socket(Socket),
- tcp_connect(Socket, localhost:Port),
- tcp_open_socket(Socket, StreamPair),
- stream_pair(StreamPair, In, Out),
- wotp_io_setup(In, Out),
- format(Out,'~N~q.~nq.~n',[ReaderPred,Pred]),
- flush_output(Out),
- setup_call_cleanup(tell(Out),Call,
- ignore(((format(Out,'~N',[]),told,ignore(catch(close(StreamPair, [force(true)]),_,true)))))).
- wotp_create_server(Port):- thread_property(_T,alias(wotp_server)),!.
- wotp_create_server(Port):-
- (wotp_server_port(Port) -> true ; asserta(wotp_server_port(Port))),
- tcp_socket(ServerSocket),
- tcp_setopt(ServerSocket, reuseaddr),
- tcp_bind(ServerSocket, Port),
- tcp_listen(ServerSocket, 5),
- thread_create(wotp_server_loop(ServerSocket), _,[ alias(wotp_server)]).
- wotp_server_loop(ServerSocket) :-
- tcp_accept(ServerSocket, Client, _Peer),
- tcp_open_socket(Client, StreamPair),
- gensym(wotp_client_,Alias),
- thread_create(wotp_service(Client, StreamPair),_,[alias(Alias),detached(true)]),
- wotp_server_loop(ServerSocket).
- wotp_service(Client, StreamPair):-
- stream_pair(StreamPair, In, Out),
- wotp_io_setup(In, Out),
- read(In,ReaderPred),read(In,Pred), debug(wotp,'~q. => ~q. ~n',[ReaderPred,Pred]),
- repeat,
- call(In,Data), debug(wotp,'~q.~n',[call(In,Data)]),
- ((Data \==end_of_file, Data \== -1 ) -> (once(call(Pred,Data)),fail) ;
- ignore(catch(close(StreamPair, [force(true)]),_,true))).
- wotp_io_setup(In, Out):-
- set_stream(In, close_on_abort(false)),
- set_stream(Out, close_on_abort(false)),
- current_prolog_flag(encoding, Enc),
- set_stream(In, encoding(Enc)),
- set_stream(Out, encoding(Enc)),
- set_stream(In, newline(detect)),
- set_stream(Out, newline(dos)).
- wotp_create_server:- (wotp_server_port(Port)->wotp_create_server(Port);wotp_create_server(16996)).
- :- source_location(S,_),forall(source_file(H,S),ignore(( \+ (predicate_property(H,PP),member(PP,[(multifile),built_in])),
- functor(H,F,A),module_transparent(F/A),export(F/A)))).
- :- wotp_create_server.
- % Example
- :- with_output_to_pred(say(dmiles), format('Hello World~n',[])).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement