使用PHP套接字发送和接收数据

前端之家收集整理的这篇文章主要介绍了使用PHP套接字发送和接收数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试通过 PHP套接字发送和接收数据.

Evrything还可以,但是当我试图发送数据时,PHP不会发送任何内容(Wireshark告诉我发送的数据长度为0).

我正在使用此代码

<?PHP
$address = 'example.com';
$port = 1234;

$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$sockconnect = socket_connect($sock,$address,$port);

$c = 0;
do {
    $c++;
    $msg = '<test>Xml data</test>';

    socket_write($sock,$msg,strlen($msg));

    echo socket_read($sock,1024 * 100,PHP_NORMAL_READ);

} while ($c < 3);

socket_close($sock);

谁能帮我?
感谢您阅读我的问题.

如果你连一次都没有检查错误,你怎么知道一切都好?

考虑以下example from the manual

<?PHP
error_reporting(E_ALL);

/* Get the port for the WWW service. */
$service_port = getservbyname('www','tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET,SOL_TCP);
if ($socket === false) {
    echo "socket_create() Failed: reason: " . 
         socket_strerror(socket_last_error()) . "\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket,$service_port);
if ($result === false) {
    echo "socket_connect() Failed.\nReason: ($result) " . 
          socket_strerror(socket_last_error($socket)) . "\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket,$in,strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket,2048)) {
    echo $out;
}

socket_close($socket);
?>

猜你在找的PHP相关文章