PHP Sockets is half-working

谁说我不能喝 提交于 2019-12-05 04:15:50

You have "plain" socket_write() and socket_read() calls. Unfortunately socket functions are unreliable by design (that's behavior inherited from BSD sockets). You can't just call socket_write() and expect it to actually write bytes (as odd as it sounds…)

PHP manual quote:

socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

You have to check how many bytes have been written and keep retrying until all you wanted has been sent.

The same goes for reading. Read call can read as much as you requested or less and you're expected to retry the call.

Make sure to set sockets to blocking and then call read/write in a loop, or use (equally awful) select() call to find which sockets may have some data or may have finished sending.


If you want API that's not such PITA, then use streams instead, which have reliable reads/writes.

If you don't necessarily need PHP, then have a look at Node JS, which is specially designed server/environment for programs with long-lived network connections.

Change

socket_write($socket, $i, strlen($i));

To:

socket_write($socket, strval($i), strlen(strval($i)));

You are providing an integer where PHP expects a string.

From one of the notes in the documentation: http://php.net/manual/en/function.socket-write.php

Some clients (Flash's XMLSocket for example) won't fire a read event until a new line is recieved.

So try changing your code:

socket_write($socket, $i, strlen($i)); to: socket_write($socket, $i.'\n', strlen($i)+1);

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!