Php socket programming

Source: Internet
Author: User
Tags php online socket error
Php socket Programming php socket programming is hard to understand. However, we only need to understand the relationship between several socket functions and their roles, so it should not be difficult to understand. in my opinion, socket programming is actually to build a network service client and server, which is the same as mysql client and server, as long as you understand what the mysql client and server are, you should be able to understand what I want to talk about below.

The network protocols, TCP, UDP, and socket three-way handshakes related to socket programming are explained in detail on the Internet, the process of setting up a socket is shown as follows:

This figure shows how hard I have stolen it from others. you must be nice-looking. at the same time, I would like to express my gratitude to the author who has been stolen from me, I apologize for stealing your image. I hope you will not care about it in large numbers. I am too lazy to draw pictures. (in fact, I am not confident in my drawing technology ).

How does socket establish a connection? As mentioned above, the connection process is essentially the same as that of the mysql client and server. What is different from mysql is that the mysql server and client have already been edited for us, and we only need to apply it. However, the key moment is coming. socket does not provide anything to us. The only thing that is provided to us is dozens of socket functions.

The implication is that socket programming requires us to create the server and client by ourselves, that is, ''socket programming ''-- that is, we need to create an application similar to mysql server and client.

Speaking of this, I would like to ask, do you say this socket is a headache? It neither creates a server nor a client for our application. we have to apply the socket function and create a network protocol application of our own, is that a headache for you? There is no way to deal with headaches. if you need your own applications, you still have to deal with socket. Well, this is just an external question. if you don't talk much about it, let's start with the question below.

Before you get confused by socket programming, I will show you several key functions of socket and explain their respective functions to you. Otherwise, if anyone who has no foundation for socket programming can see it, I am afraid that after reading it, I will skip this article decisively, and then I will be afraid of the fear of socket. Haha, let's talk about it again.

Socket key function 1:

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

Purpose: Create a socket. to put it bluntly, it is a network data stream.

Returned value: a socket, or false. if the parameter is incorrect, the E_WARNING warning is issued.

Php's online manual makes it clearer:

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

The above statement was copied from the php online manual. No. does this mean that the client and the server mentioned above are exactly the same? Haha.

Parameter 1: network protocol,

What are the network protocols? The options are as follows:

AF_INET: IPv4 network protocol. Both TCP and UDP can use this protocol. This is 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 (inter-process communication ).

Parameter 2: socket stream. options include:

SOCK_STREAM SOCK_DGRAM SOCK_SEQPACKET SOCK_RAW SOCK_RDM.

Here only the first two are explained:

SOCK_STREAM TCP socket.

SOCK_DGRAM UDP socket.

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

Parameter 3: protocol. options include:

SOL_TCP: TCP protocol.

SOL_UDP: UDP protocol.

It can be seen from this that, in fact, the second parameter of the socket_create function is associated with the third parameter.

For example, assume that the first parameter applies the IPv4 protocol: AF_INET, and the second parameter applies the TCP socket: SOCK_STREAM,

So the third parameter must use SOL_TCP, which is not hard to understand.

TCP socket, of course, can only use TCP, isn't it? If you apply UDP socket, I will not talk about how to choose the third parameter, huh, you know.

Key function 2:

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

Purpose: connect to a socket. The return value is true or false.

Parameter 1: function return value of socket_create

Parameter 2: IP address

Parameter 3: port number

Key function 3:

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

Purpose: bind a socket. The return value is true or false.

Parameter 1: function return value of socket_create

Parameter 2: IP address

Parameter 3: port number

Key function 4:

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

Purpose: listen to a socket, and the returned value is true or false.

Parameter 1: function return value of socket_create

Parameter 2: maximum number of listening sockets

Key functions 5:

Socket_accept ($ socket)

Function: Receives the resource information of the socket. the socket information resource is returned successfully. if the socket information resource fails, the value false is returned.

Parameter: return value of socket_create function

Key functions 6:

Socket_read ($ socket)

Purpose: Read the resource information of the socket,

Returned value: the socket resource is successfully converted to string information, and the failure value is false.

Parameter: return value of the socket_create or socket_accept function

Key functions 7:

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

Purpose: write data into the socket.

Returned value: the length of the string in bytes. if the string fails to be returned, the return value is false.

Parameter: return value of the socket_create or socket_accept function

Key Functions 8:

Socket_close ($ socket)

Purpose: disable socket

Return value: true is returned for success, and false is returned for failure.

Parameter: return value of the socket_create or socket_accept function

These eight functions are the core functions of socket. The following lists two important functions.

Socket_last_error ($ socket). the parameter is the return value of socket_create. it is used to obtain the last error code number of the socket and return the socket code.

Socket_strerror ($ code). the parameter is the return value of the socket_last_error function to obtain the string information of the code. the returned value is the Socket Error information.

These two functions are very important in socket programming. when writing socket programming, I think you still have to use them, especially for new users. they can be used for debugging.

    

The following is the code. pay attention to it. please check out my comments carefully. comments are important. comments are important. you have to shout out important things three times.

Server script, D: \ vhost \ test \ socket \ server_socket.php

 

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

  1, "usec" => 0); // The maximum timeout time for sending a set of streams is 6 seconds. socket_set_option ($ socket, SOL_SOCKET, SO_SNDTIMEO, array ("sec" => 6, "usec" => 0);/***************** set the socket connection option, you can skip these two steps to ************* // connect to the socket stream of the server, this step is to establish a connection between the client and the server's socket stream if (socket_connect ($ socket, '123. 0.0.1 ', 8888) = false) {echo 'connect fail massege :'. socket_strerror (socket_last_error ();} else {$ message = 'L love you I love socket '; // Convert it to GBK encoding to handle garbled code, this depends on your Encoding. each person's encoding is different. $ message = mb_convert_encoding ($ message, 'gbk', 'utf-8 '); // write 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; // read the stream information returned by the server while ($ callback = socket_read ($ socket, 1024) {echo 'server return message is :'. PHP_EOL. $ callback ;}} socket_close ($ socket); // after the work is completed, close the stream set.

How can we test these two scripts?

Open the dos window in windows, that is, the cmd black window, and then run php D: \ vhost \ test \ socket \ server_socket.php,

Let the black windows on the server continue to run,

Second, the php client script can be run in a browser, or in another cmd black window.

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

Note: The php running name must be added to the windows environment variable. if you do not know how to add it,

Go to the php running command directory and run it with absolute commands. you can also add the php command to the environment variable.

Here is my situation. your file address may be different from mine. please follow your address. Otherwise, you will be at your own risk.

As mentioned above, socket programming must have a server to communicate with each other. Therefore, the black window of the server must be kept open.

Note:

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

This function is used to set Data Stream options for sockets or a very important function.

Parameter 1: return value of the socket_create or socket_accept function

Parameter 2: SOL_SOCKET. it seems that only this option is available.

Parameter 3 is associated with parameter 4,

Parameter 3 can be: SO_REUSEADDR SO_RCVTIMEO S0_SNDTIMEO

Explanations:

SO_REUSEADDR is used immediately after the Socket port is released.

If this parameter is set to parameter 3, parameter 4 can be set to true or false.

SO_RCVTIMEO is the maximum timeout time for receiving resources of the socket.

SO_SNDTIMEO is the maximum timeout time of the socket sending resource.

If parameter 3 is the two, parameter 4 is an array like this ('SEC '=> 1, 'usec' => 500000)

The maximum timeout time is set in the array. However, the unit is seconds and the unit is microsecond.

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.