Simple understanding of PHP socket Programming "NET pick"

Source: Internet
Author: User
Tags php online socket error

PHP socket programming is more difficult to understand, but we just understand the socket of the relationship between several functions, as well as 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 , which is the same as the MySQL client and server, you just have to understand what the MySQL client and server are all about, and you should be able to understand what I'm going to say.

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 online have a very detailed explanation, here do not say, only a socket to set up the process diagram of the socket to let you see:

This figure is my hard work from other people to steal from, you must look well, at the same time, here I also to that was stolen by my author thanked, I stole your pattern to apologize, but also hope you adults a large number of don't care ah. I was too lazy, too lazy to draw, (in fact, their own drawing technology expressed not self-confidence, hehe).

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

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

Speaking of which, I would like to ask, do you think this socket is a headache for people? It does not set up a server, and do not set up a client to our application, it is not to let us to apply the socket function, to create a belong to our own network protocol socket application, this is not very annoying you? There is no way to headache, if you need your own application, you still have to deal with the socket. Oh, this is just a digression, not much to say, the following into the topic.

Before you get caught up in the socket programming, I'll show you some of the key functions of the socket and explain how they work. Otherwise, if the socket programming is not the basis for people to see, I am afraid you see, then decisively skipped 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)

Role: Create a socket socket, plainly speaking, is a network data stream.

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

The online manual for PHP is more clearly said:

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

The previous sentence was copied from the PHP online manual. See no, here is the meaning is not and I repeatedly mentioned above the client and the server is exactly the same? Oh.

The parameter 1 is: network protocol,

What are the network protocols? It has the following three options:

Af_inet:ipv4 network protocol. Both TCP and UDP can use this protocol. It's generally used, you know.

Af_inet6:ipv6 network protocol. Both TCP and UDP can use this protocol.

Af_unix: Local communication protocol. High-performance and low-cost IPC (interprocess communication).

Parameter 2: Socket flow, options are:

Sock_stream sock_dgram sock_seqpacket sock_raw SOCK_RDM.

Only the first two are explained here:

Sock_stream TCP protocol sockets.

SOCK_DGRAM UDP protocol sockets.

For more information please link here: http://php.net/manual/zh/function.socket-create.php

Parameter 3:protocol protocol, options are:

SOL_TCP:TCP protocol.

SOL_UDP:UDP protocol.

As can be seen here, in fact the second parameter of the Socket_create function and the third parameter is associated.

For example, if your first parameter applies the IPV4 protocol: Af_inet, then the second parameter applies 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, can only use the TCP protocol, is not it? If you apply a UDP socket, then the third parameter is how to choose I will not say, hehe, you understand.

Key function 2:

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

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

function return value for 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: Binds a socket with a return value of TRUE or False

function return value for parameter 1:socket_create

Parameter 2:ip Address

Parameter 3: Port number

Key function 4:

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

Function: Listens on a socket and returns a value of TRUE or False

function return value for parameter 1:socket_create

Parameter 2: Maximum number of listener sockets

Key function 5:

Socket_accept ($socket)

Function: Receives the resource information of the socket, successfully returns the information resource of the socket, and fails to false

Parameter: function return value of Socket_create

Key function 6:

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

Function: Reads the resource information of the socket,

Return value: Successfully converted a socket's resource to a string information, failed to false

function return value of parameter 1:socket_create or socket_accept

Parameter 2: Length of the Read string

Key function 7:

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

Function: Writes data to the socket

Return value: The byte length of the string successfully returned, failed to false

function return value of parameter 1:socket_create or socket_accept

Parameter 2: string

Parameter 3: Length of string

Key function 8:

Socket_close ($socket)

Function: Close socket

Return value: Successful return True, failed to false

Parameter: function return value of socket_create or socket_accept

These eight functions are the core function of the socket, the following list two more important functions

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

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

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

    

Here is the code, note, please carefully read my comments, comments are important, comments are important, comments are important, important things to shout three times, hehe.

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

<?PHP//Create the socket socket stream for the server, the net protocol is the Ipv4,protocol protocol Tcp$socket = socket_create (AF_INET,SOCK_STREAM,SOL_TCP); /* BIND received socket stream host and port, relative to client/if (Socket_bind ($socket, ' 127.0.0.1 ', 8888) = = False) {echo ' server bind fail: '. Socket_st        Rerror (Socket_last_error ()); /* Here 127.0.0.1 is tested on localhost, if you have more than one computer, you can write IP address */}//Listener Socket stream if (Socket_listen ($socket, 4) ==false) {echo ' server list    En fail: '. Socket_strerror (Socket_last_error ());    }//let the server unlimited access to the information sent by the client do{/* receive the message from the client */$accept _resource = socket_accept ($socket);        The function of/*socket_accept is to accept the socket stream sent by the host Socket_bind () ()/if ($accept _resource!== false) {/* Read the resource passed by the client and convert it to a string *.        $string = Socket_read ($accept _resource,1024); /*socket_read's role is to read out the resources of socket_accept () and convert it to a string */Echo ' server receive is: '. $string. Php_eol;//php_eol the newline predefined constant for PHP if ($string! = False) {$return _client = ' server receive is: '. $string.            Php_eol;     /* Writes information to the socket_accept socket stream, which is the host client that the feedback message binds to Socket_bind () */       Socket_write ($accept _resource, $return _client,strlen ($return _client));        The function of the/*socket_write is to write information to the socket_create's socket stream, or to write to Socket_accept's socket stream */}else{echo ' socket_read is fail ';    The function of/*socket_close is to close the socket_create () or socket_accept () established by the socket stream */socket_close ($accept _resource); }}while (True); Socket_close ($socket);

Tip: Note that the execution order of the socket_bind,socket_listen,socket_accept three functions above cannot be changed, which means

The socket_bind must be executed before the Socket_listen is executed, and the final execution socket_accept

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

<?php//Create a socket socket stream $socket = socket_create (AF_INET,SOCK_STREAM,SOL_TCP); /**************** Set the socket connection option, these two steps you can omit the maximum timeout time of the *************///Receive socket stream 1 seconds, followed by a microsecond unit timeout, set to zero, indicating whether it socket_set_option     ($socket, Sol_socket, So_rcvtimeo, Array ("SEC" = 1, "usec" and "= 0)");    The maximum timeout time for sending a socket stream is 6 seconds socket_set_option ($socket, Sol_socket, So_sndtimeo, Array ("SEC" = 6, "USEC" + 0)); /**************** Set the socket connection option, these two steps you can omit the *************///connection service side of the socket stream, this step is to make the client and the server-side socket flow to establish a contact if (Socket_connect ($    Socket, ' 127.0.0.1 ', 8888) = = False) {echo ' Connect fail massege: '. Socket_strerror (Socket_last_error ());        }else{$message = ' L love your socket ';        To GBK encoding, processing garbled problem, it depends on your coding situation, everyone's code is different $message = mb_convert_encoding ($message, ' GBK ', ' UTF-8 '); Writes string information to the server if (Socket_write ($socket, $message, strlen ($message)) = = False) {echo ' fail to write '. socket_        Strerror (Socket_last_error ()); }else{Echo ' Client write success '.Php_eol; Reads the socket stream information returned by the server while ($callback = Socket_read ($socket, 1024x768)) {echo ' Server return message is: '.            Php_eol. $callback; }}} socket_close ($socket);//work is complete, close the socket stream

How do you test these two scripts?

First open the Windows DOS window, which is the CMD black window, then, run PHP D:\vhost\test\socket\server_socket.php,

Let the black windows of the server continue to run,

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

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

Note here: PHP This run name must be added to the environment variables of windows, if you do not know how to add,

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

Here is my case, your file address may not be the same as I, please follow your address situation to operate, otherwise, the consequences, hehe

As already mentioned above, socket programming must have the service side to communicate, so the service side of the black window must keep it open.

PostScript Supplement:

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

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

function return value of parameter 1:socket_create or socket_accept

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

Explain:

SO_REUSEADDR is allowed to be reused immediately after the socket port is released

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

So_rcvtimeo is the maximum timeout for receiving resources for a socket

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

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

Array is the maximum time to set timeout, however, one is the second unit, one is a microsecond unit, the function is the same

Simple understanding of PHP socket Programming "NET pick"

Related Article

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.