我正在尝试将字符串写入套接字。我想写的字符串是
SET 4 1
这是我写入套接字的函数
function write_to_socket($socket, $msg)
{
$sock = socket_create(AF_UNIX, SOCK_STREAM, 0) or die("socket_create() failed: reason: ".socket_strerror(socket_last_error()));
echo '<br>socket created<br>';
socket_connect($sock, $socket) or die("socket_create() failed: reason: ".socket_strerror(socket_last_error()));
echo 'Connected to '.$socket.'<br><br>';
$length = strlen($msg);
while (true)
{
echo 'Going to write '.$msg.'<br>';
$sent = socket_write($sock, $msg, $length);
//echo 'Read '.socket_read($sock, $length).'<br>';
if ($sent === FALSE)
{
echo "could not write<br>";
break;
}
// Check if the entire message has been sent
if ($sent < $length) {
// If not sent the entire message.
// Get the part of the message that has not yet been sented as message
$msg = substr($msg, $sent);
// Get the length of the not sented part
$length -= $sent;
echo $length." more characters need to be writte<br>";
}
else
{
echo "Finished writing<br>";
break;
}
}
echo 'Done writing '.$msg;
socket_close($sock);
}
此功能输出
socket created
Connected to /tmp/cool_socket
Going to write SET 4 1
Finished writing
Done writing SET 4 1
我遇到的问题是4 1被写入套接字但SET没有。我正在收听套接字并打印任何打印到它的消息。因此,一旦我将SET 4 1
发送到套接字,套接字程序就输出4 1.我究竟做错了什么以及为什么SET不发送?
我调用函数的代码是这个
$i = 1;
define("RESTART", " 4");
define("SOCKET_DIRECTORY", '/tmp/');
$msg = "SET".RESTART." ".($i);
write_to_socket(SOCKET_DIRECTORY.get_socket_name($i), $msg);
其中get_socket_name($ i)每次返回cool_socket,无论我发送什么值。
感谢任何人的帮助。