Home » Php » php – Nonblocking sockets: Are messages queued?

php – Nonblocking sockets: Are messages queued?

Posted by: admin July 12, 2020 Leave a comment

Questions:

As I understand, it is possible to create a nonblocking network socket in PHP 5.x.

But what happens if a script sends several long messages using the same nonblocking socket as follow:

socket_write($socket, $string1, $length);
socket_write($socket, $string2, $length);
socket_write($socket, $string3, $length);
socket_write($socket, $string4, $length);

Are these messages queued (on the sender/receiver side?) or is it possible that the receiver gets parts of different messages because they sent “parallel”?

For example: Is is possible that the receiver gets 10 bytes of $string1, then 30 bytes of $string2, then another 25 bytes of $string1 … and so on….

How to&Answers:

It depends on the protocol that the socket is using. See socket_create for the possible types of sockets. The main types are UDP and TCP:

udp The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.

tcp The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

To answer your question directly, TCP sockets will guarantee in-order delivery, whereas UDP sockets will not.