TCP編程
1.涉及的模塊和函數(shù)
%gen_tcp是TCP編程的核心模塊
%包括函數(shù)如下
-spec connect(Address, Port, Options, Timeout) -> {ok, Socket} | {error, Reason} when
Address = inet:socket_address() | inet:hostname() %其實(shí)可以是字符串
Port = inet:port_number()%整形
Options = [connect_option()]%舉例:[binary,{packet,0},{nodelay,true}]
Timeout = timeout()%超時(shí)時(shí)間
Socket = socket()
Reason = timeout | inet:posix()
-spec listen(Port, Options) -> {ok, ListenSocket} | {error, Reason} when
Port = inet:port_number()
Options = [listen_option()]
ListenSocket = socket()
Reason = system_limit | inet:posix()
-spec accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason} when
ListenSocket = socket()
%Returned by listen/2.
Timeout = timeout()
Socket = socket()
Reason = closed | timeout | system_limit | inet:posix()
-spec recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason} when
Socket = socket()
Length = integer() >= 0
Timeout = timeout()
Packet = string() | binary() | HttpPacket
Reason = closed | timeout | inet:posix()
HttpPacket = term()
-spec send(Socket, Packet) -> ok | {error, Reason} when
Packet = string() | binary() | HttpPacket
-spec shutdown(Socket, How) -> ok | {error, Reason} %關(guān)閉連接
Socket = socket()
How = read | write | read_write
Reason = inet:posix()
%當(dāng)How==read時(shí)寫的操作還是可以進(jìn)行的鹿寨,反之,=write時(shí)讀的操作還可以進(jìn)行薪夕,
%如果HOW==READ或Socket端口中沒有緩沖傳出數(shù)據(jù)脚草,則立即關(guān)閉套接字并在Reason中返回遇到的任何錯(cuò)誤。如果套接字端口中有緩沖數(shù)據(jù)原献,則會延遲關(guān)閉套接字的嘗試馏慨,直到將數(shù)據(jù)寫入內(nèi)核套接字發(fā)送緩沖區(qū)埂淮。如果遇到任何錯(cuò)誤,則關(guān)閉套接字并在下一個(gè)recv / 2或send / 2上返回 {error写隶,closed}倔撞。
-spec close(Socket) -> ok 和shutdown差不多,但是shutdown更好,將會即刻關(guān)閉
服務(wù)端:
%來個(gè)實(shí)例吧:服務(wù)端;每進(jìn)入一個(gè)客戶就創(chuàng)建一個(gè)新進(jìn)程去Accept和loopRecv
-module(tcpServer).
-export([start/0]).
start()->
case gen_tcp:listen(6612,[binary,{packet,4},{active,false}]) of%創(chuàng)建一個(gè)被動服務(wù)器
{ok,Socket}->
io:format("Server Listen Success!~n"),
loopAccept(Socket);
{error,Reason}->
io:format("Server Listen Fail! Reason~p~n",Reason)
end.
loopAccept(Socket)->
case gen_tcp:accept(Socket) of
{ok,ClientFd}->
spawn(tcpServer,fun()->loopAccept(ClientFd) end),
loopRecv(ClientFd);
{error,Reason}->
io:format("Server Accept Fail! Reason~p~n",Reason)
end.
loopRecv(ClientFd)->
case gen_tcp:recv(ClientFd,0) of
{ok,Bin}->
io:format("Recv:~p~n",[binary_to_list(Bin)]),
loopRecv(ClientFd);
{error,closed}->
byebye
end.
客戶端:
%This is a client
-module(tcpClient).
-export([start/1,loopSend/3]).
-spec start(Num)-> any() when
Num:integer().
start(Num)->
case gen_tcp:connect({127,0,0,1},6612,[binary,{packet,4}]) of
{ok,Socket}->
loopSend(Socket,0,Num);
{error,Reason}->
Reason
end.
loopSend(Socket,Index,Target) when Target=<Index ->
io:format("Send Finish!~n",[]);
loopSend(Socket,Index,Target)->
gen_tcp:send(Socket,list_to_binary(["This is a message!!"])),
loopSend(Socket,Index+1,Target).