|
一般來說網(wǎng)絡(luò)通訊常用的方式有2種:文本通訊和二進(jìn)制通訊。php與erlang之間實(shí)現(xiàn)文本通訊比較簡(jiǎn)單,這里就不做討論,本文主要討論的是php與erlang實(shí)現(xiàn)二進(jìn)制通訊的實(shí)現(xiàn)方法。實(shí)現(xiàn)步驟如下:
erlang端代碼:
復(fù)制代碼 代碼如下:-module(server).
-export([start/0]).
-define( UINT, 32/unsigned-little-integer).
-define( INT, 32/signed-little-integer).
-define( USHORT, 16/unsigned-little-integer).
-define( SHORT, 16/signed-little-integer).
-define( UBYTE, 8/unsigned-little-integer).
-define( BYTE, 8/signed-little-integer).
-define( PORT, 5678).
%% 啟動(dòng)服務(wù)并接受客戶端的連接
start() ->
{ok, LSock} = gen_tcp:listen(?PORT, [binary, {packet, 0},{active, false}]),
io:format("socket listen: ~p on ~p ~n",[LSock, ?PORT]),
accept(LSock).
accept(LSock) ->
{ok, ASock} = gen_tcp:accept(LSock),
spawn(fun() -> server_loop(ASock) end),
accept(LSock).
server_loop(ASock) ->
case gen_tcp:recv(ASock, 0) of
{ok, <<Len:?USHORT,Cmd:?USHORT,Contain:4/binary-unit:8>> = A} ->
io:format("recv data: ~p ~p ~p~n", [Len, Cmd, Contain]),
%%將接收到數(shù)據(jù)發(fā)送回客戶端
gen_tcp:send(ASock, A),
server_loop(ASock);
{ok, Data} ->
io:format("recv unformated data: ~p~n", [Data]),
server_loop(ASock);
{error, _} ->
{ok, recv_error}
end.
php端代碼:
<?php$timeout = 3;//超時(shí)時(shí)間:3秒$fp = fsockopen("tcp://127.0.0.1", 5678, $errno, $errstr, $timeout/* 連接超時(shí)時(shí)間 */);if (!$fp) { echo "$errstr ($errno)<br />/n";} else { stream_set_timeout($fp, $timeout); //遠(yuǎn)程數(shù)據(jù)接收或發(fā)送超時(shí)時(shí)間 $format = "vva4"; $data = pack($format, 4, 10001, "abcd"); //$data 按照一定格式被打包成二進(jìn)制數(shù)據(jù) fwrite($fp, $data); if (!feof($fp)) { $rs = fread($fp, 1024); //讀取遠(yuǎn)程數(shù)據(jù) if ($rs) { $len = strlen($rs); //$len 可以獲取數(shù)據(jù)的長(zhǎng)度,用以計(jì)算content的長(zhǎng)度 //在這個(gè)例子中,content 的長(zhǎng)度為 4 $format = "vlen/vcmd/a4content"; $data = unpack($format, $rs); print_r($data); } else { echo "timeout!"; } } else { echo "timeout!"; } fclose($fp);}?>
運(yùn)行正常的情況下,php端會(huì)顯示以下內(nèi)容:
Array ( [len] => 4 [cmd] => 10001 [content] => abcd )
針對(duì)通訊的一些說明:
這里用到的是php的pack函數(shù)和unpack函數(shù):
pack函數(shù):將數(shù)據(jù)按照一定格式打包成二進(jìn)制數(shù)據(jù),生成的數(shù)據(jù)接近C/C++的結(jié)構(gòu)體數(shù)據(jù)(C/C++字符串帶結(jié)束符)。
unpack函數(shù):與pack相反,對(duì)二進(jìn)制數(shù)據(jù)進(jìn)行解包。
對(duì)應(yīng)的erlang端,則直接用位語法來匹配二進(jìn)制數(shù)據(jù)即可。
php技術(shù):php實(shí)現(xiàn)與erlang的二進(jìn)制通訊實(shí)例解析,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。