Advertisement
Guest User

Untitled

a guest
Jan 29th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.27 KB | None | 0 0
  1.  
  2. % :- dynamic .
  3.  
  4.  
  5.  
  6.  
  7. create_server(Port) :-
  8.   tcp_socket(Socket),
  9.   tcp_bind(Socket, Port),
  10.   tcp_listen(Socket, 5),
  11.   acceptor_loop(Socket).
  12.  
  13. on_thread_exit(Ip) :-
  14.   writeln(user_error, "Exiting On Socket Closed!"),
  15.   format(user_error,"Disconnection from: ~w\n",[Ip]),
  16.   flush_output(user_error).
  17.  
  18. % the client handling threaad doesn't die on error from the socket
  19. % need to make this happen I think
  20. acceptor_loop(Socket) :-
  21.   tcp_accept(Socket,Client,Ip),
  22.   thread_create(handle_client(Client,Ip),ThreadId,[at_exit(on_thread_exit(Ip))]),
  23.   format("Connection from: ~w\n",[Ip]),
  24.   flush_output,
  25.   acceptor_loop(Socket).
  26.  
  27. output(Stream,String) :-
  28.   string_concat(String,"\r",Line),
  29.   writeln(Stream,Line),
  30.   flush_output(Stream).
  31.  
  32. handle_client(Client,Ip) :-
  33.   % thread_at_exit((writeln("DO WE EXIT?!"),flush_output)),
  34.   tcp_open_socket(Client,Stream),
  35.   output(Stream,"Welcome to Prolog Communications!"),
  36.   client_loop(Stream).
  37.  
  38. client_loop(Stream) :-
  39.   read_string(Stream, "\n", "\r", End, Line),
  40.   ( End == -1 ->
  41.  
  42.     writeln("Exiting thread...."),
  43.     thread_exit("Socket Closed") ;
  44.  
  45.     output(Stream,Line),
  46.     % close(Stream),
  47.     writeln("everything is fine, looping for more input..."),
  48.     client_loop(Stream)).
  49.  
  50. start :- create_server(8000).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement