php实现与erlang的二进制通讯实例解析
一般来说网络通讯常用的方式有2种:文本通讯和二进制通讯。php与erlang之间实现文本通讯比较简单,这里就不做讨论,本文主要讨论的是php与erlang实现二进制通讯的实现方法。实现步骤如下:
erlang端代码:
-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).
%%启动服务并接受客户端的连接 start()-> {ok,LSock}=gen_tcp:listen(?PORT,[binary,{packet,0},{active,false}]), io:format("socketlisten:~pon~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)-> casegen_tcp:recv(ASock,0)of {ok,<<Len:?USHORT,Cmd:?USHORT,Contain:4/binary-unit:8>>=A}-> io:format("recvdata:~p~p~p~n",[Len,Cmd,Contain]), %%将接收到数据发送回客户端 gen_tcp:send(ASock,A), server_loop(ASock); {ok,Data}-> io:format("recvunformateddata:~p~n",[Data]), server_loop(ASock); {error,_}-> {ok,recv_error} end.