Php 通过套接字发送2个请求
我正在尝试向同一连接发送2个响应。但我在发送时遇到问题。有时第二个请求丢失 有人能帮助确保第二个请求在同一个连接上正确进行吗 出于某种原因,我的克莱特接受了两个请求。 1.邮件计数。 2.要显示的消息Php 通过套接字发送2个请求,php,sockets,tcp,Php,Sockets,Tcp,我正在尝试向同一连接发送2个响应。但我在发送时遇到问题。有时第二个请求丢失 有人能帮助确保第二个请求在同一个连接上正确进行吗 出于某种原因,我的克莱特接受了两个请求。 1.邮件计数。 2.要显示的消息 $valCount = str_pad(strlen($message), 4, "0", STR_PAD_LEFT); socket_write($socket, $valCount) or die("[" . @date('H:i:s') ."] Could not send output\n
$valCount = str_pad(strlen($message), 4, "0", STR_PAD_LEFT);
socket_write($socket, $valCount) or die("[" . @date('H:i:s') ."] Could not send output\n");
socket_write($socket, $message) or die("[" . @date('H:i:s') ."] Could not send output\n");
请注意,
socket\u write()。从:
socket\u write()
不一定从给定缓冲区写入所有字节。根据网络缓冲区等,虽然缓冲区较大,但只写入一定数量的数据(甚至一个字节)是有效的。您必须小心,以免无意中忘记传输其余数据
函数将返回一个整数,该整数描述成功发送的字节数。您需要检查返回值以确保正确发送所有数据
大概是这样的:
// An array of the messages to send
$messagesToSend = array();
$messagesToSend[] = str_pad(strlen($message), 4, "0", STR_PAD_LEFT);
$messagesToSend[] = $message;
// Loop the message queue
foreach ($messagesToSend as $data) {
// Loop while still data to send
while ($data) {
// Send data
$bytesSent = socket_write($socket, $data);
// Check for failures
if ($bytesSent === FALSE) {
die("[".date('H:i:s')."] Could not send output (".socket_strerror(socket_last_error($socket)).")\n");
}
// Trim the data that was sent off $data
// This approach means that the while() loop will finish when all the data
// has been sent - $data will be an empty string so will evaluate to FALSE
$data = substr($data, $bytesSent);
} // while
} // foreach
请注意,socket\u write()。从:
socket\u write()
不一定从给定缓冲区写入所有字节。根据网络缓冲区等,虽然缓冲区较大,但只写入一定数量的数据(甚至一个字节)是有效的。您必须小心,以免无意中忘记传输其余数据
函数将返回一个整数,该整数描述成功发送的字节数。您需要检查返回值以确保正确发送所有数据
大概是这样的:
// An array of the messages to send
$messagesToSend = array();
$messagesToSend[] = str_pad(strlen($message), 4, "0", STR_PAD_LEFT);
$messagesToSend[] = $message;
// Loop the message queue
foreach ($messagesToSend as $data) {
// Loop while still data to send
while ($data) {
// Send data
$bytesSent = socket_write($socket, $data);
// Check for failures
if ($bytesSent === FALSE) {
die("[".date('H:i:s')."] Could not send output (".socket_strerror(socket_last_error($socket)).")\n");
}
// Trim the data that was sent off $data
// This approach means that the while() loop will finish when all the data
// has been sent - $data will be an empty string so will evaluate to FALSE
$data = substr($data, $bytesSent);
} // while
} // foreach
我观察到,当您在本地机器上编程套接字时(客户机和服务器都在同一台机器上),会发生这种情况
我的代码有两个从服务器发送到客户机的响应,第一个响应是缓冲的(不是实际发送的),当第二个请求到达时,所有响应一起发送到客户机
因此,您的字符串可能有两个附加在一起的响应。
如果是这种情况,那么您不必担心,因为当服务器和客户端位于不同的机器上时,这种情况不会发生。我观察到,当您在本地机器上编程套接字时(客户端和服务器都位于同一机器上),这种情况会发生
我的代码有两个从服务器发送到客户机的响应,第一个响应是缓冲的(不是实际发送的),当第二个请求到达时,所有响应一起发送到客户机
因此,您的字符串可能有两个附加在一起的响应。
如果是这种情况,那么您不必担心,因为当服务器和客户端位于不同的机器上时,这种情况不会发生。很可能是套接字写入工作做得很好,问题在于接收代码。但是,如果没有任何适当的调试尝试,这只是一个猜测。很可能套接字写入工作做得很好,问题出在接收代码上。但如果没有任何适当的调试尝试,这只是一个猜测。