第17章 套接字程式設計

2021-09-01 11:58:30 字數 2759 閱讀 2331

1.使用tcp從伺服器獲取資料

end.2.乙個簡單的tcp伺服器

%%socket_server.erl:

-module(socket_server).

-export([start_nano_server/0,loop/1,nano_client_eval/1]).

start_nano_server() ->

=gen_tcp:listen(2345,[binary,,,]),

=gen_tcp:accept(listen),

gen_tcp:close(listen),

loop(socket).

loop(socket) ->

receive

->

io:format("server received binary =~p~n",[bin]),

str=binary_to_term(bin),

io:format("server (unpacked) ~p~n",[str]),

reply=lib_misc:string2value(str),

io:format("server replying=~p~n",[reply]),

gen_tcp:send(socket,term_to_binary(reply)),

loop(socket);

->

io:format("server socket closed~n")

end.

nano_client_eval(str) ->

=gen_tcp:connect("localhost",2345,[binary,]),

ok=gen_tcp:send(socket,term_to_binary(str)),

receive

->

io:format("client received binary =~p~n",[bin]),

val=binary_to_term(bin),

io:format("client result =~p~n",[val]),

gen_tcp:close(socket)

end.

3.順序和並行伺服器

4.注意點:

5.主動和被動套接字

6.套接字錯誤處理

7.udp

%應用示例:乙個udp階乘伺服器

-module(udp_test).

-export([start_server/0,client/1]).

start_server() ->

spawn(fun() -> server(4000) end).

%伺服器

server(port) ->

=gen_udp:open(port,[binary]),

io:format("server opened socket:~p~n",[socket]),

loop(socket).

loop(socket) ->

receive

=msg ->

io:format("server received:~p~n",[msg]),

n=binary_to_term(bin),

fac=fac(n),

gen_udp:send(socket,host,port,term_to_binary(fac)),

loop(socket)

end.

fac(0)->1;

fac(n) ->n* fac(n-1).

%客戶端

client(n) ->

=gen_udp:open(0,[binary]),

io:format("client opened socket=~p~n",[socket]),

ok=gen_udp:send(socket,"localhost",4000,term_to_binary(n)),

value=receive

=msg ->

io:format("client received:~p~n",[msg]),

binary_to_term(bin)

after 2000 ->

0end,

gen_udp:close(socket),

value.

8.udp資料報可能會二次傳輸,所以可呼叫erlang的內建函式make_ref,可以確保返回乙個全域性唯一的引用.

套接字程式設計基礎 Unix網路程式設計第3章總結

1.套接字位址結構 以下是其posix定義 struct in addr struct sockaddr in在rhel5中,in addr t是無符號32位整數,in.h檔案中包含 typedef unit32 t in addr t posix規範只有sin family,sin port和si...

3章 套接字程式設計簡介

套接字程式設計都會用到套接字位址,這裡講述一些基本的系統呼叫函式,非常的簡單,這裡可以好好思考。呼叫函式給被呼叫函式分配空間,然後傳遞指標給呼叫函式填充結構空間。用於儲存當前連線的一些關鍵資訊。define sockaddr common sa prefix sa family t sa prefi...

TCP IP 第1章 理解網路程式設計和套接字

1.socket函式建立套接字。2.呼叫bind函式給套接字分配ip位址和埠號。3.呼叫listen函式轉為可接受請求狀態。4.呼叫accept函式受理連線請求 include include include include include include using namespace std v...