php 使用PHP socket发送和接收数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8967850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use PHP socket to send and receive data
提问by ucha
I'm trying to send and receive data by PHP socket.
我正在尝试通过 PHP 套接字发送和接收数据。
Evrything is OK but when I'm trying to send data PHP does not send anything (Wireshark told me that sent data length was 0).
一切正常,但是当我尝试发送数据时,PHP 不发送任何内容(Wireshark 告诉我发送的数据长度为 0)。
I'm using this code:
我正在使用此代码:
<?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);
Can anyone help me? Thanks for reading my question.
谁能帮我?感谢您阅读我的问题。
回答by sanmai
How can you know that everything is okay if you don't check for errors even once?
如果您一次都不检查错误,您怎么知道一切正常?
Consider the following 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, SOCK_STREAM, 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, $address, $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);
?>
回答by user3245415
You are not using the gethostbyname function, so it tries to connect to a nonexistent ip address
您没有使用 gethostbyname 函数,因此它尝试连接到不存在的 IP 地址
<?php
$address= gethostbyname('yourdata.com');