PHP utilizes Stream_socket_server and stream_socket_client

Source: Internet
Author: User
Tags socket

Above PHP for the server, it will listen for messages until pressed: Ctrl + C
while (true)
{
Execute once every 5 seconds
Receive_message (' 127.0.0.1 ', ' 85 ', 5);
}
Custom functions to get messages
function Receive_message ($ips tutorial erver, $portnumber, $nbsecondsidle)
{
Create a socket
$socket =stream_socket_server (' tcp://'. $ipserver. ': $portnumber, $errno, $ERRSTR);
if (! $socket)
{
If you create a socket failed output
echo "$errstr ($errno) <br/>n";
}
Else
{
Accept socket connection and get information if the creation succeeds
while ($conn = @stream_socket_accept ($socket, $nbsecondsidle))
{
$message =read ($conn, 1024);
Echo ' I have received that: '. $message;
Fputs ($conn, "okn");
Fclose ($conn);
}
Fclose ($socket);
}
}
Server End
?>
<?php
The following code is the client, which sends the message and reads the reply
Send_message (' 127.0.0.1 ', ' n ', ' message to send ... ');
Custom functions, sending information
function Send_message ($ipserver, $portserver, $message)
{
$FP =stream_socket_client ("tcp://$ipserver: $portserver", $errno, $ERRSTR);
if (! $fp)
{
echo "Erreur: $errno-$errstr <br/>n";
}
Else
{
Fwrite ($fp, "$messagen");
$response = Fread ($fp, 4);
if ($response!= "OKN")
{
echo ' command couldn ' t be executed...ncause: '. $response;
}
Else
{
echo ' execution successfull ... ';
}
Fclose ($FP);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.