Generally speaking, there are 2 kinds of methods used in network communication: Text communication and binary communication. The text communication between PHP and Erlang is relatively simple, there is no discussion here, this article mainly discusses the implementation of binary communication between PHP and Erlang. The implementation steps are as follows:
Erlang End Code:
Copy Code code as follows:
-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 service and accept client connections
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]),
Percent% will receive data sent back to client
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-Side code:
<?php
$timeout = 3;
Timeout: 3 sec
$fp = fsockopen ("tcp://127.0.0.1", 5678, $errno, $ERRSTR, $timeout/* Connection Timeout * *);
if (! $fp) {
echo "$errstr ($errno) <br/>\n";
} else {
stream_set_timeout ($fp, $timeout);
Remote data receive or send timeout
$format = "VVA4";
$data = Pack ($format, 4, 10001, "ABCD");
$data are packaged into binary data
fwrite ($FP, $data) in a certain format;
if (!feof ($fp)) {
$rs = fread ($fp, 1024);
Read Remote Data
if ($rs) {
$len = strlen ($rs);
$len can get the length of the data to calculate the length of the content/
/In this case, the content length is 4
$format = "Vlen/vcmd/a4content";
$data = Unpack ($format, $rs);
Print_r ($data);
else {
echo ' timeout! ';}}
else {
echo ' timeout! ';
}
Fclose ($FP);
>
When it's working, the PHP side will display the following:
Array ([Len] => 4 [cmd] => 10001 [content] => ABCD)
Some instructions for communication:
Here is the PHP pack function and the unpack function:
Pack function: The data is packaged into binary data in a certain format, and the resulting data is close to the C + + structure data (c + + string with the Terminator).
Unpack function: In contrast to pack, unpack binary data.
corresponding to the Erlang end, the direct use of bit syntax to match binary data .