Home > Net >  Send data packet over TCP using PHP socket
Send data packet over TCP using PHP socket

Time:11-12

I want to send a command to a third party server over TCP protocol, in their documentation they listed the following command data format:

Syntax Bytes Value
card_id 4 0x12345678
param1 2 0
param2 1 1
param3 1 0
time 4 time_t corresponding to 2004-6-1 13:00:00
data_len 1 08
data_body Variable (determinedby data_len) "12345678"

I want to use socket_write function in php to send the packet, so my question is how can I convert these values to send it?

Firstly: I convert each value to hexadecimal then I put it together into one string variable (each byte represent 2 hex characters). For example: 1 will be 01 if value is on 1 byte / 1 will be 0001 if value is on 2 bytes

Secondly: I convert each value to binary(01) then I put it together into one string variable (each byte represent 8 bit). For example: 1 will be 00000001 if value is on 1 byte / 1 will be 00000000 000000001 if value is on 2 bytes

Please can anyone help me to know how can I represent the command data to send over tcp socket in php ? I am a bit confused.

CodePudding user response:

Use the pack() function to encode a number of values as bytes of a string.

$packet = pack('NnCCNCa*', $card_id, $param1, $param2, $param3, $time, $data, $data);
  • N = unsigned 4-byte number
  • n = unsigned 2-byte number
  • C = unsigned byte
  • a* = string

The 4-byte and 2-byte formats are big-endian, which corresponds to network byte order.

  • Related