このディレクトリの索引
http://toro.2ch.net/test/read.cgi/tech/1339338438/61
#  [1] 授業単元: c言語  
#  [2] 問題文(含コード&リンク):違うPCからテキストファイルをダウンロードするプログラムを作れ。  
#                サーバでファイルを一行ずつ読み込み送信する。クライアントでは受信をしてファイルに書き込む。 
#  

server :-
        open_server(Socket,NewSocket),
        open_server_stream(NewSocket,Instream,Outstream),
        server_to_client(Insteam,Outstream,Instream_2),
        close_server_stream(Instream,Outstream),
        close_server_socket(Socket,NewSocket).

open_server(Port,Socket,NewSocket) :-
        socket(internet,stream,Socket),
        socket_bind(Socket,Port),
        socket_listen(Socket),
        socket_accept(Socket,Host:Port2,NewSocket).

open_server_stream(Newsocket,Instream,Outstream) :-
        open(NewSocket,read,Instream),
        open(NewSocket,write,Outstream).

server_to_client(Insteam,Outstream,Instream_2) :-
        get_file_name(Instream,File),
        open(File,read,Instream_2),
        server_to_client(Instream_2,Outstream),
        close(Instream_2).

get_file_name(Instream,File,Outstream) :-
        get_line(Instream,Line),
        sub_atom(Line,0,4,_,'GET '),
        split(Line,['"'],[_,File|_]),
        write(Outstream,'OK filename\n\n').

server_to_client(Instream_2,Outstream) :-
        at_end_of_stream(Instream_2),!.
server_to_client(Instream_2,Outstream) :-
        get_char(Instream_2,Char),
        put_char(Outstream,Char),
        server_to_client(Instream_2,Outstream).

close_server_stream(Instream,Outstream) :-
        close(Instream),
        close(Outstream).

close_server_socket(Socket,NewSocket) :-
        socket_shutdown(Socket),
        socket_shutdown(NewSocket).

client(Host,Port,File) :-
        open_client(Host,Port,Socket),
        filecopy(Socket,File),
        close_client(Socket,Instream,Outstream).

open_client(Host,Port,Socket,Instream,Outstream) :-
        socket(internet,stream,Socket),
        socket_connect(Socket, Host : Port),
        open(Socket,read,Instream),
        open(Socket,write,Outstream).

file_copy(Socket,File,Instream,Outstream) :-
        writef(Outstream,'%t\n',[File]),
        file_copy(Instream,Outstream,Outstream_2).

close_client(Socket,Instream,Outstream) :-
        close(Instream),
        close(Outstream),
        socket_shutdown(Socket).

file_copy(Instream,Outstream,File,Outstream_2) :-
        open(File,write,Outstream_2),
        セッション_1(Instream,Outstream),
        セッション_2(Instream,Outstream,Outstream_2),
        close(Outstream_2).

セッション_2(Instream,Outstream_2) :-
        at_end_of_stream(Instream),!.
セッション_2(Instream,Outstream_2) :-
        get_line(Instream,Line),
        writef(Outstream_2'%t\n',[Line]),
        セッション_2(Instream,Outstream_2).

セッション_1(Instream,Outstream) :-
        writef('GET %t\n\n',[File]),
        get_line(Instream,Line_1),
        get_line(Instream,''),
        sub_atom(Line_1,0,4,_,'GET ').