PHP writes TCP server and client programs

Source: Internet
Author: User

1, modify php.ini, open Extension=php_sockets.dll

2. Service-side program socketserver.php

<?php//Ensure that the client is connected without time-out set_time_limit (0);    Set the IP and port number $address = "127.0.0.1";   $port = 3046; /** * Create a socket * af_inet= is IPv4 if using IPv6, the parameter is Af_inet6 * Sock_stream is the TCP type of socket, if UDP then use SOCK_DGRAM */$sock = Socket_create (Af_inet, Sock_stream, sol_tcp) or Die ("Socket_create () fail:". Socket_strerror (Socket_last_error ()).    "/n"); Blocking mode Socket_set_block ($sock) or Die ("Socket_set_block () Fail:"). Socket_strerror (Socket_last_error ()).    "/n"); Bind to the socket port $result = Socket_bind ($sock, $address, $port) or Die ("Socket_bind () Fail:"). Socket_strerror (Socket_last_error ()).    "/n"); Start listening $result = Socket_listen ($sock, 4) or Die ("Socket_listen () Fail:"). Socket_strerror (Socket_last_error ()).    "/n"); echo "ok\nbinding the socket on $address: $port ...    ";    echo "Ok\nnow ready-to-accept connections.\nlistening on the socket ... \ n"; Do {//Never stop the daemon//it receives the connection request and invokes a sub-connection socket to handle the information between the client and the server $msgsock = socket_accept ($sock)Or Die ("Socket_accept () Failed:reason:". Socket_strerror (Socket_last_error ()).        "/n");            while (1) {//reads the client data echo "read-client" \ n "; The Socket_read function reads the client data until it encounters the \n,\t or the/s character.            The PHP script considers this character to be the input terminator.            $buf = Socket_read ($msgsock, 8192);            echo "Received msg: $buf \ n";              if ($buf = = "Bye") {//Receive the end message, close the connection, wait for the next connection socket_close ($msgsock);          Continue            }//Data transfer writes The returned result to the client $msg = "Welcome \ n"; Socket_write ($msgsock, $msg, strlen ($msg)) or Die ("Socket_write () Failed:reason:". Socket_strerror (Socket_last_error ()). "                /n ");    }} while (true);    Socket_close ($sock);   ?>

3. Client program socketclient.php

<?php    set_time_limit (0);        $host = "127.0.0.1";    $port = 3046;    $socket = Socket_create (Af_inet, Sock_stream, sol_tcp) or Die ("Could not create  socket\n");         $connection = Socket_connect ($socket, $host, $port) or Die ("Could not connet server\n");   Socket_write ($socket, "hello socket") or Die ("Write failed\n");  while ($buff = Socket_read ($socket, 1024x768, Php_normal_read)) {        echo ("Response was:". $buff. "\ n");      Echo ("Input want to say to the server:\n");      $text = fgets (STDIN);      Socket_write ($socket, $text);  }    Socket_close ($socket);  ? >  

4. Testing

Running the service-side program: C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\SocketServer.php

Running the client program: C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\SocketClient.php

If you encounter

Fatal error:call to undefined function socket_create (). 1. Find the php.ini and see   if the Extension=php_gd2.dll and  Extension=php_sockets.dll extensions are open; 2. Look at the contents of the Phpinfo () display, Whether the socket module is enable; I checked it and found it all in line. But the error still occurs? What's going on here? Later I found that the original is what I saw in the Phpinfo () and the cmd window used in the PHP is not the same thing. The reason is that I have installed PHP several times. The previous PHP registered path within the system's environment variables. So the cmd window is used in the previous PHP. The current PHP settings are shown in Phpinfo (). The solution is very simple, the system environment variable in the path, pointing to the old PHP paths to the PHP used to point to the path. So php in cmd and PHP in the browser is the same thing. That's it.

5, its process and C very similar, is actually encapsulated C socket.

Excerpt from: http://blog.csdn.net/anda0109/article/details/46655301

PHP writes TCP server and client programs

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.