Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable length packets in php

Tags:

php

sockets

I am receiving packets sent to my server through UDP. I am using socket_read to read the data and it is coming along just fine. I have run into an error however. The length parameter to socket_read in my case is NOT always the same. The length of the data can range anywhere from 50-150 bytes. One thing that remains constant is that the data set is ended with a \x00 byte. How would I get the read function to always read until encountering this byte? I have already tried PHP_NORMAL_READ flag, but the docs say it only ends at \n or \r which really isn't what I want (tried it it doesn't work for my data). At the same time, the php page for socket_read states in the length parameter description that,

The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).

The type says nothing about the /0 byte. Its like a piece of documentation is missing. What I need is a function that will either let me specify a delimiter for my data, will automatically read all the data from the socket that is available. There might be a solution in the socket_recv function but its undocumented and I don't know how it works.

Thanks in advance.

like image 959
Samuel Avatar asked Jan 29 '09 21:01

Samuel


2 Answers

If I understand correctly, you want to read data from a socket until there is no more data to read, with the problem being that the amount of data is variable and you don't know when to stop.

According to the relevant manual page (http://php.net/socket_read):

Note: socket_read() returns a zero length string ("") when there is no more data to read.

You should be able to deal with variable-length data by reading byte-by-byte until you hit a zero-length string:

while (($currentByte = socket_read($socket, 1)) != "") {
    // Do whatever you wish with the current byte
}
like image 195
Jon Cram Avatar answered Oct 16 '22 12:10

Jon Cram


Hav you tried something like this:

do {
    echo socket_read($handle,1024);
    $status = socket_get_status($handle);
} while($status['unread_bytes']);
like image 1
Tim Avatar answered Oct 16 '22 13:10

Tim