This example describes the PHP socket Communication (TCP/UDP) method. Share to everyone for your reference, specific as follows:
Attention
1. When the Socket_bind IP address can not really loop address such as 127.0.0.1
2.server.php backstage run up nohup php server.php >/var/tmp/a.log 2>&1 &
One: UDP mode
1) server.php
<?php
//error_reporting (e_all);
Set_time_limit (0);
Ob_implicit_flush ();
$socket = Socket_create (Af_inet, Sock_dgram, sol_udp);
if ($socket = = False) {
echo socket_create () Failed:reason: ". Socket_strerror (Socket_last_error ()). "\ n";
}
$ok = Socket_bind ($socket, ' 202.85.218.133 ', 11109);
if ($ok = = False) {
echo socket_bind () Failed:reason: ". Socket_strerror (Socket_last_error ($socket));
while (true) {
$from = "";
$port = 0;
Socket_recvfrom ($socket, $BUF, 1024, 0, $from, $port);
echo $buf;
Usleep (1000);
>
2) client.php
<?php
$sock = socket_create (Af_inet, Sock_dgram, sol_udp);
$msg = ' Hello ';
$len = strlen ($msg);
Socket_sendto ($sock, $msg, $len, 0, ' 202.85.218.133 ', 11109);
Socket_close ($sock);
? >
Two: TCP mode
1) server.php
<?php
//error_reporting (e_all);
Set_time_limit (0);
Ob_implicit_flush ();
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp);
Socket_bind ($socket, ' 192.168.2.143 ', 11109);
Socket_listen ($socket);
$ACPT =socket_accept ($socket);
echo "acpt!\n";
while ($ACPT) {
$words =fgets (STDIN);
Socket_write ($ACPT, $words);
$hear =socket_read ($ACPT, 1024);
echo $hear;
if ("bye\r\n" = = $hear) {
socket_shutdown ($ACPT);
break;
Usleep (1000);
}
Socket_close ($socket)
?>
2) client.php
<?php
$socket = socket_create (Af_inet, Sock_stream, sol_tcp);
$con =socket_connect ($socket, ' 192.168.2.143 ', 11109);
if (! $con) {socket_close ($socket); exit;}
echo "link\n";
while ($con) {
$hear =socket_read ($socket, 1024);
echo $hear;
$words =fgets (STDIN);
Socket_write ($socket, $words);
if ($words = = "bye\r\n") {break;}
}
Socket_shutdown ($socket);
Socket_close ($sock);
? >
More about PHP Interested readers can view the site topics: "PHP Socket Usage Summary", "PHP basic Grammar Introductory Course", "PHP error and Exception handling method summary" and "PHP common functions and Skills summary"
I hope this article will help you with the PHP program design.