PHP Socket Programming Process detailed

Source: Internet
Author: User

Service side (server.php)

//Set some variables$host = "127.0.0.1"; $port = 25003;//don ' t timeout!set_time_limit (0);//Create Socket$socket = S Ocket_create (af_inet, sock_stream, 0) or die ("Could not create socket\n");//bind socket to Port$result = Socket_bind ($soc  Ket, $host, $port) or Die ("Could not bind to socket\n");//start listening for connections$result = Socket_listen ($socket, 3) or Die ("Could not set up socket listener\n"),//Accept incoming connections//spawn another socket to handle Communica Tion$spawn = socket_accept ($socket) or Die ("Could not accept incoming connection\n");//Read Client Input$input = Socket_r EAD ($spawn, 1024x768) or Die ("Could not read input\n");//clean up input string$input = Trim ($input); echo "Client Message:". $input;//Reverse client input and send back$output = Strrev ($input). "\ n"; Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not write output\n");//Close Socketssocket_close ($ Spawn); Socket_close ($socket); 



Client (client.php)

$host    = "127.0.0.1"; $port    = 25003; $message = "Hello server"; echo "message to Server:" $message;//Create socket$ Socket = Socket_create (af_inet, sock_stream, 0) or die ("Could not create socket\n");//connect to Server$result = Socket_c Onnect ($socket, $host, $port) or Die ("Could not connect to server\n");  Send string to Serversocket_write ($socket, $message, strlen ($message)) or Die ("Could not send data to server\n");//Get Server Response$result = Socket_read ($socket, 1024x768) or Die (' Could not read server response\n '); echo "Reply from Server
   : ". $result;//Close Socketsocket_close ($socket);

After creating the above files (server.php and client.php), do the following:

    1. Copy these files from the WWW directory (assuming wamp), and place them in C:\wamp.
    2. Open a Web browser and type localhost in the address bar.
    3. Browse server.php First and then client.php.

PHP Socket Programming Process detailed

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.