Developing C/s structure with PHP

Source: Internet
Author: User
Tags bind error handling php server socket strlen port number

Server

<?php
Server
Set error handling
Error_reporting (E_all);
Set run time
Set_time_limit (0);
Buffering
Ob_implicit_flush ();
$ip = "127.0.0.1"; IP Address
$port = 1000; Port number
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp); Create a SOCKET
if ($socket)
echo "Socket_create () successed!\n";
Else
echo "Socket_create () failed:". Socket_strerror ($socket). " \ n ";
$bind = Socket_bind ($socket, $ip, $port); Bind a socket
if ($bind)
echo "Socket_bind () successed!\n";
Else
echo "Socket_bind () failed:". Socket_strerror ($bind). " \ n ";
$listen = Socket_listen ($socket); Inter Listening socket
if ($listen)
echo "Socket_listen () successed!\n";
Else
echo "Socket_listen () failed:". Socket_strerror ($listen). " \ n ";
while (true)
{
$msg = Socket_accept ($socket); Accept a socket
if (! $msg)
{
echo "Socket_accept () failed:". Socket_strerror ($msg). " \ n ";
Break
}
$welcome = "Welcome to PHP server!\n";
Socket_write ($msg, $welcome, strlen ($welcome));
while (true)
{
$command = Strtoupper (Trim (Socket_read ($msg, 1024));
if (! $command)
Break
Switch ($command)
{
Case "HELLO":
$writer = "Hello everybody!";
Break
Case "QUIT":
$writer = "Bye-bye";
Break
Case "Help":
$writer = "Hello\tquit\thelp";
Break
Default
$writer = "Error command!";
}
Socket_write ($msg, $writer, strlen ($writer));
if ($command = = "QUIT")
Break
}
Socket_close ($msg);
}
Socket_close ($socket); Close socket
?>

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.