First, your server should be able to connect to socket server ip and port. a socket port was provision for client to connect in socket.
Once you have established your connection, you can now follow the simple steps below for you to be able to develop a socket client in PHP.
1. Define the socket server ip and port.
$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';
2. Create a TCP/IP socket. to get the error, you can use socket_sterror() function passing the error code parameter using socket_last_error().
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo socket_sterror(socket_last_error());
3. After the socket was successfully created, you can now send input data request using socket_write() function, parameters are the created socket object, the input data request, and the input data length.
$in = "<input data request>";
$len = strlen($in);
socket_write($socket, $in, $len);
4. To get the return data of the socket server request from no.3, you can use socket_read() function, parameters are the socket and the maximum length of the binary data.
$out = socket_read($socket, 2048);
5. And lastly, closing the socket by socket_close() function.
socket_close($socket);
Hope you were able to follow the steps above, you can try the complete code below, just define the socket server ip and port with a valid input data request.
<?php
error_reporting(E_ALL);
/* define socket server ip and port here.. */
$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';
/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
$error = socket_strerror(socket_last_error());
echo "socket_create() failed: [$result] $error\n";
} else {
echo "socket_create() ok.\n";
}
/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
$error = socket_strerror(socket_last_error($socket));
echo "socket_connect() failed: [$result] $error\n";
} else {
echo "socket_connect() ok.\n";
}
$in = "<input data request>";
$len = strlen($in);
echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";
echo "reading return data.\n";
while ($out = socket_read($socket, 2048)) {
echo "socket_read() : $out";
}
echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>
No comments:
Post a Comment