PHP Socket programming Detailed _php Tips

Source: Internet
Author: User
Tags php online set socket strlen

PHP socket programming is more difficult to understand things, but, as long as we understand the relationship between several functions of the socket, and the role they play, then it should not be difficult to understand, in my opinion, socket programming, in fact, is to establish a Network service client and server , this is the same as the client and server side of MySQL, you should be able to understand what I am going to tell you as long as you understand the client and server side of MySQL.

About the socket programming involved in the network protocol, what TCP Ah, UDP ah, what socket three times handshake and so on, these network protocols have a very detailed interpretation of the Internet, here does not say, only cut a socket to establish a socket process diagram let you see:


This picture is I worked hard from others to steal cut over, you must look good, at the same time, here I also to that I steal screenshots of the author expressed gratitude, I steal your logo to apologize, but also hope that you adults a large number of don't care ah. I am really too lazy, too lazy to draw, (in fact, the drawing of their own technology to express self-confidence, hehe).

How does the socket establish the connection? As mentioned above, the process of establishing a connection is the same as the nature of the connection to MySQL's client and server. And it is different from MySQL, MySQL server and client have been edited for us, we only need to apply on the line. But, the key moment comes, the socket it has nothing to offer us, the only offer to us is: dozens of socket functions.

The implication is that the socket programming is to create our own server and client, that is, ' socket programming '--is to build a MySQL-like server and client applications.

Speaking of which, I would like to ask, you say this socket makes people have a headache? It does not establish a service side, also does not establish a client to our application, we must let ourselves to apply the socket function, to create a network protocol for our own application, this is not a headache for you? There is no way to have a headache, if you need your own application, you still have to deal with the socket. Oh, this is just a digression, not much said, the following into the business.

Before you get caught up in the socket programming, I'm going to show you some key functions of the socket and explain their respective roles. Otherwise, if there is no basis for the socket programming people see, I am afraid you read, the decisive skip this article, from the socket to create a phobia. Oh, and more said.

Key function of socket 1:

Socket_create ($net parameter 1, $stream parameter 2, $protocol parameter 3)

Function: Create a socket socket, plainly, is a network data flow.

Return value: A socket, or FALSE, parameter error issuing e_warning warning

The online Handbook for PHP is more clearly stated:

Socket_create creates and returns a socket, also known as a communication node. A typical network connection is composed of 2 sockets, one running on the client and the other running on the server side.

The above sentence is copied from the PHP online Handbook. See, does this mean that the client and the server that I mentioned over and over are exactly the same? Oh.

Parameter 1 is: network protocol,

What are the network protocols? Its selection is on the following three:

Af_inet:ipv4 network protocol. This protocol can be used by both TCP and UDP. Usually use this, you know.

Af_inet6:ipv6 network protocol. This protocol can be used by both TCP and UDP.

Af_unix: Local communication protocol. IPC with high performance and low cost (interprocess communication).

Parameter 2: Socket stream, options are:

Sock_stream sock_dgram sock_seqpacket sock_raw SOCK_RDM.

This only explains the first two:

Sock_stream TCP protocol sockets.

SOCK_DGRAM UDP protocol sockets.

For more information please link here:

Parameter 3:protocol protocol, options are:

SOL_TCP:TCP agreement.

SOL_UDP:UDP agreement.

It can be seen from here that the second and third parameters of the Socket_create function are related.

For example, if your first parameter applies the IPV4 protocol: Af_inet, then the second parameter is applied to the TCP socket: Sock_stream,

Then the third parameter must be sol_tcp, which should not be difficult to understand.

TCP protocol sockets, of course, only the TCP protocol, right? If you apply the UDP socket, then the third parameter how to choose I will not say, oh, you understand.

Key function 2:

Socket_connect ($socket parameter 1, $ip parameter 2, $port parameter 3)

Function: Connect a socket, return a value of TRUE or False

function return value of parameter 1:socket_create

Parameter 2:ip Address

Parameter 3: Port number

Key function 3:

Socket_bind ($socket parameter 1, $ip parameter 2, $port parameter 3)

Function: Bind a socket, return a value of TRUE or False

function return value of parameter 1:socket_create

Parameter 2:ip Address

Parameter 3: Port number

Key function 4:

Socket_listen ($socket parameter 1, $backlog parameter 2)

Function: Listen for a socket, return a value of TRUE or False

function return value of parameter 1:socket_create

Parameter 2: Maximum number of listening sockets

Key function 5:

Socket_accept ($socket)

Function: Receive socket resource information, successfully return socket information resource, fail to False

Parameters: Socket_create function return value

Key function 6:

Socket_read ($socket parameter 1, $length parameter 2)

Function: Reads the socket's resource information,

Return value: Successfully converts a socket's resource to string information and fails to false

Parameter 1:socket_create or socket_accept function return value

Parameter 2: Length of the string read

Key function 7:

Socket_write ($socket parameter 1, $msg parameter 2, $strlen parameter 3)

Function: Writes data to the socket

Return value: Successfully returns the byte length of the string, failing to False

Parameter 1:socket_create or socket_accept function return value

Parameter 2: string

Parameter 3: Length of string

Key function 8:

Socket_close ($socket)

Function: Close socket

Return value: Success returns True and fails to false

Parameters: function return value of socket_create or socket_accept

These eight functions are the core functions of the socket, with two more important functions listed below

Socket_last_error ($socket), the return value of the parameter socket_create, is to get the last error code number of the socket, return the value socket code

Socket_strerror ($code), the parameter is the return value of the Socket_last_error function, gets the string information of the code, and the return value is the error message of the socket.

These two functions in the socket programming is still very important, in writing socket programming, I think you still have to use, especially novice, can be used as a trial


The following is the code, pay attention to, please look at my comments, comments are important, annotations are important, annotations are important, important things to yell three times, hehe.

Server-side scripting, D:\vhost\test\socket\server_socket.php

<?php//Create the socket socket stream of the service port, net protocol for the IPV4,PROTOCOL protocol for TCP $socket = socket_create (AF_INET,SOCK_STREAM,SOL_TCP); /* Binding received socket host and port, corresponding to the client * * if (Socket_bind ($socket, ' ', 8888) = = False) {echo ' server bind fail: '. Socket_strerr
    or (Socket_last_error ()); * * Here is the in the local host test, if you have more than one computer, you can write IP address////Listen to the socket stream if (Socket_listen ($socket, 4) ==false) {echo ' Server listen FAI
  L: '. Socket_strerror (Socket_last_error ());
  //Let the server unlimited access to the information sent by the client do{/* received the information from the client/* * * $accept _resource = socket_accept ($socket); The role of/*socket_accept is to accept socket_bind () bound by the host sent over the socket/if ($accept _resource!== false) {/* Read the resources passed by the client, and converted to a string * * $str
    ing = Socket_read ($accept _resource,1024); The role of/*socket_read is to read the resource of socket_accept () and convert it into a string/echo ' server receive is: '. $string. Php_eol;//php_eol for PHP newline predefined constant if ($string!= false) {$return _client = ' server receive is: '. $string.
      Php_eol; /* Writes the information to the socket_accept socket, which is the feedback message to the host client that Socket_bind () binds to Socket_write ($accept _resource, $retUrn_client,strlen ($return _client));
    The function of/*socket_write is to write information to the socket_create socket stream or to write information to the SOCKET_ACCEPT socket/}else{echo ' socket_read is fail ';
  The function of the/*socket_close is to close the socket_create () or socket_accept () the established socket Flow/socket_close ($accept _resource);
}}while (True); Socket_close ($socket);

Tip: Note that the order of execution of the above socket_bind,socket_listen,socket_accept three functions cannot be changed, i.e.

The socket_bind must be executed before the Socket_listen is executed before the socket_accept

Client script, D:\vhost\test\socket\client_socket.php

<?php//Create a socket sleeve stream $socket = Socket_create (AF_INET,SOCK_STREAM,SOL_TCP); /**************** Set socket connection options, these two steps you can omit the *************///Receive socket maximum timeout of 1 seconds, followed by the microsecond unit timeout, set to zero, indicating that regardless of its socket_set_option
   ($socket, Sol_socket, So_rcvtimeo, Array ("SEC" => 1, "USEC" => 0));
  The maximum timeout for sending a socket stream is 6 seconds socket_set_option ($socket, Sol_socket, So_sndtimeo, Array ("SEC" => 6, "USEC" => 0)); /**************** Set socket connection options, these two steps you can omit the *************///connection service side of the socket flow, this step is to make the client and server-side sockets establish contact if (Socket_connect $
  Socket, ' ', 8888) = = False) {echo ' Connect fail massege: '. Socket_strerror (Socket_last_error ());
    }else{$message = ' L Loving you I love your socket ';
    To GBK encoding, dealing with garbled problems, depending on your coding situation, everyone's coding is different $message = mb_convert_encoding ($message, ' GBK ', ' UTF-8 '); Writes the string information to the server if (Socket_write ($socket, $message, strlen ($message)) = = False) {echo ' fail to write '. Socket_strerro

    R (Socket_last_error ()); }else{Echo ' Client write success '.
      Read the socket stream information returned from the service sidewhile ($callback = Socket_read ($socket, 1024)) {echo ' Server return: '.
      Php_eol. $callback; }} socket_close ($socket);//finished working, closing the socket stream

How do you test these two scripts?

First open Windows DOS window, is cmd Black window, then, run PHP D:\vhost\test\socket\server_socket.php,

Let the service end of the black window run continuously,

Second, PHP client script can be run through the browser, you can open a cmd black window to run

PHP D:\vhost\test\socket\client_socket.php

Please note here: PHP This run name must be added to Windows environment variables, if you do not know how to add,

Please enter the PHP Run command directory to run with absolute command, you can also Baidu to add PHP commands to environment variables

Here is my case, your file address may be different from mine, please follow your address situation to operate, otherwise, the consequences of conceit, hehe

As has been said above, socket programming must have a server to communicate, so the server side of the black window is to keep it open.

PostScript Supplement:

Socket_set_option ($socket parameter 1, $level parameter 2, $optname parameter 3, $optval parameter 4)

The function is to set the data flow option for the socket, or a very important function.

Parameter 1:socket_create or socket_accept function return value

Parameter 2:sol_socket, as if only this option

Parameter 3 is associated with parameter 4,

Parameter 3 can be: so_reuseaddr So_rcvtimeo S0_sndtimeo


SO_REUSEADDR is a socket port that can be reused immediately after it is released

Parameter 3 If this is the case, then parameter 4 can be true or false

So_rcvtimeo is the maximum timeout for a socket's receive resource

So_sndtimeo is the maximum timeout for a socket's sending resource

Parameter 3 If this is the two, then parameter 4 is an array of such arrays (' sec ' =>1, ' usec ' =>500000)

The maximum time to set the timeout is in the array, but one is a second unit and the other is a microsecond unit.

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: 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.