Reputation: 390
Never used socket before. I have to make socket to get an answer from server in json format. This is code:
$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , $host , $port))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
var_dump($buf);
socket_close($sock);
And this is response I get:
- Socket created
- Connection established
- Message send successfully
- Warning: socket_recv(): unable to read from socket [10045]: The attempted operation is not supported for the type of object
referenced. in C:\wamp64\www\json\index.php on line 73- Could not receive data: [10045] The attempted operation is not supported for the type of object referenced.
So it seems socket_recv returns false. why? Is that because of json object in response from server? And how to fix that? Any directions?
Upvotes: 0
Views: 1004
Reputation: 15376
UDP unlike TCP is a connectionless protocol, which means that two ends can exchange messages without having to establich a communication channel.
So, it's best to use socket_recvfrom
and socket_sendto
because they work well with not connection-oriented sockets.
$host = '11.11.11.1';//for example
$port = 1111;
$message = "xgm";
set_time_limit(2);
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_sendto($sock, $message, strlen($message), 0, $host, $port)){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
if(socket_recvfrom($sock , $buf , 2045 , 0, $host, $port) === FALSE){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
var_dump($buf);
socket_close($sock);
Upvotes: 1