9

I'm trying to send and receive data by PHP socket.

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).

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.

2 Answers 2

9

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);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

There is no any errors, but remote host does not answer me again. But it works correctly when I'm sending data via SocketTest v3.0
Yes it works on the other hosts, but I need to send only xml data, because my host does not respond http head requests from any ports except 1980. It does not respond me (even using your example) when I'm sending XML data.
Well, that is not a PHP problem here.
But SocketTest (written on java) working properly when using same OS, same data, same host. I've compared data sent by PHP to data sent by SocketTest (wireshark) and all sent package is same.
3

You are not using the gethostbyname function, so it tries to connect to a nonexistent ip address

<?php
$address= gethostbyname('yourdata.com');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.