Detailed PHP socket Communication _php Skills

Source: Internet
Author: User
Tags bind closure php code php script set socket socket error strlen

For TCP/IP, UDP, Socket programming These words you are not very strange, right? With the development of network technology, these words are filled with our ears.

So what is TCP/IP, UDP?
TCP/IP (Transmission Control protocol/internet Protocol), the Transmission Control Protocol/Internetwork Protocol, is an industrial standard protocol set that is designed for wide area networks (WANs).
UDP (User data Protocol, Subscriber Datagram Protocol) is a protocol corresponding to TCP. It is a part of the TCP/IP protocol family.
Here is a diagram that shows the relationship of these protocols.

The TCP/IP protocol family includes transport layer, network layer and link layer. Now you know the relationship between TCP/IP and UDP.
where is the socket?
In Figure 1, we don't see the socket shadow, so where is it? Or use the diagram to speak, at a glance.

The original socket is here.
What is a socket?
the socket is the intermediate software abstraction layer of the application layer communicating with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, which is the complex TCP/IP protocol family hidden behind the socket interface, for users, a group of simple interface is all, let the socket to organize data to meet the specified protocol.
Will you use them?
Predecessors have done a lot of things to us, the network communication between a lot of simple, but after all, there are quite a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as the understanding of the work of socket programming, the veil of mystery will be uncovered.
A scene in life. You have to call a friend, dial first, the friend heard the phone call after the phone, then you and your friend set up a connection, you can talk. And so on, hang up the phone and end this conversation. The life of the scene explains how this works, perhaps the TCP/IP protocol family is born in life, this is not necessarily.

Start with the server side. The server side initializes the socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, and waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), if the connection succeeds, then the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, and then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction.

Socket related functions:
Socket_accept () accepts a socket connection
Socket_bind () binds the socket to an IP address and port
Socket_clear_error () Clears the socket error or the last error code
Socket_close () closes a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () opens a socket listener on the specified port
Socket_create_pair () produces a pair of indistinguishable sockets into an array
Socket_create () produces a socket, which is equivalent to generating a socket data structure
Socket_get_option () Get socket option
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () adds a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure capable of sending and receiving read and write
Socket_iovec_delete () deletes an already allocated Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () frees a Iovec resource
Socket_iovec_set () sets the Iovec data new value
Socket_last_error () Gets the last error code for the current socket
Socket_listen () listens for all connections by the specified socket
Socket_read () reads the specified length of data
SOCKET_READV () reads data coming from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket and, if not specified, the default current socket
Socket_recvmsg () received a message from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends data to the connected socket
SOCKET_SENDMSG () Send message to socket
Socket_sendto () sends a message to the socket at the specified address
Socket_set_block () is set to block mode in the socket
Socket_set_nonblock () socket is set to not block mode
Socket_set_option () Set socket options
Socket_shutdown () This function allows you to close a read, write, or specified socket
Socket_strerror () returns a detailed error for the specified error number
Socket_write () write data to the socket cache
Socket_writev () write data to a scatter/aggregate array

Case ONE: Socket communication Demo

Server side:

 1 <?php 2//ensures that the client is not timed out 3 set_time_limit (0); 4 5 $ip = ' '; 6 $port = 1935; 7 8/* 9 +-------------------------------* @socket communication throughout the process +-------------------------------* @socket_create 13 * @socket_bind * @socket_listen @socket_accept * @socket_read * @socket_write 19 +- -------------------------------/*----------------The following operations are in the manual-------------------* * ($sock = SOCKET_CR Eate (af_inet,sock_stream,sol_tcp)) < 0) {echo "socket_create () failed because of:". Socket_strerror ($sock). " \ n "; ($ret = Socket_bind ($sock, $ip, $port)) < 0) {echo "socket_bind () the reason for the failure is:". Socket_strerror ($ret). " \ n "; if ($ret = Socket_listen ($sock, 4)) < 0) {echo "Socket_listen () the reason for the failure is:". Socket_strerror ($ret). " \ n "; $count = 0; ($msgsock = socket_accept ($sock)) < 0) {socket_accept echo "() Failed:reason:". Socket_strerror ($msgsock). "\ n"; break; /else {42 43//HairTo the client $msg = "Test success!" \ n "; Socket_write ($msgsock, $msg, strlen ($msg)); The echo "Test succeeded AH \ n"; $buf = Socket_read ($msgsock, 8192); $talkback = "received information: $BUF \ n"; Echo $talkback; The IF (+ + $count >= 5) {a break; 56}; //echo $buf; Socket_close ($msgsock); +} while (true); Socket_close ($sock); ?>

This is the service-side code for the socket. Then run CMD, note that your program to store the path AH.

No reflection, the current server-side program has started to run, the port has started listening. Run Netstat-ano can view port condition, mine is 1935 port

Look, the port is already in the listening state. Next we can just run the client program to connect. On the Code

 1 <?php 2 error_reporting (E_all); 3 Set_time_limit (0); 4 echo " 

The client is already connected to the server.

Case two: Code detailed

Set some basic variables
$host = "";
$port = 1234;
Set timeout time
set_time_limit (0);
Create a socket
$socket = socket_create (af_inet, sock_stream, 0) or die ("could not createsocket\n");
Bind socket to port
$result = Socket_bind ($socket, $host, $port) or die ("could not bind tosocket\n");
Start listening for links
$result = Socket_listen ($socket, 3) or die ("could not set up socketlistener\n");
Accept incoming Connections
//Another socket to handle communication
$spawn = socket_accept ($socket) or die ("could not accept incom Ingconnection\n ");
Gets the input from the client
$input = Socket_read ($spawn, 1024) or die ("could not read input\n");
Empty the input string
$input = Trim ($input);
Processes client input and returns the result
$output = Strrev ($input). "\ n";
Socket_write ($spawn, $output, strlen ($output)) or die ("could not write
Closure of sockets
Socket_close ($spawn);
Socket_close ($socket);

The following is a detailed description of each of its steps:

1. The first step is to create two variables to hold the IP address and port of the server on which the socket is running. You can set your own server and port (this port can be a number between 1 and 65535), provided that the port is not in use.

[Copy to Clipboard]

Set two variables
$host = "";

2. The Set_time_out () function can be used on the server side to ensure that PHP does not timeout waiting for client connections.

[Copy to Clipboard]

Timeout time

3. On the previous basis, it is time to use the Socket_creat () function to create a socket-this function returns a socket handle that will be used in all subsequent functions.

[Copy to Clipboard]

a socket $socket = Socket_create (af_inet, sock_stream, 0) or die ("could not create

The first argument "Af_inet" is used to specify a domain name;
The second argument "Sock_strem" tells the function what type of socket (in this case, the TCP type) will be created.

Therefore, if you want to create a UDP socket, you can use the following code:

[Copy to Clipboard]

a socket $socket = Socket_create (af_inet, SOCK_DGRAM, 0) or die ("could not create

4. Once a socket handle is created, the next step is to specify or bind it to the specified address and port. This can be done through the Socket_bind () function.

[Copy to Clipboard]

Bind socket to specify address and port
$result = Socket_bind ($socket, $host, $port) or die ("could not bind to"

5. When the socket is created and bound to a port, you can start listening for external connections. PHP allows you to start a listener by the Socket_listen () function, and you can specify a number (in this case, the second parameter: 3)

[Copy to Clipboard]

Start listening for connection
$result = Socket_listen ($socket, 3) or die ("could not set up socket

6. Until now, your server is basically doing nothing but waiting for a connection request from the client. Once a client connection is received, the socket_accept () function begins to work, receiving the connection request and invoking another child socket to handle the client-server information.

[Copy to Clipboard]

Accept Request Link
//call child socket processing information
$spawn = socket_accept ($socket) or die ("could not accept incoming

This child socket can now be used by subsequent client-server communications.

7. When a connection is established, the server waits for the client to send some input information, which can be obtained by the Socket_read () function and assigned to the PHP $input variable.

[Copy to Clipboard]

Read client input
$input = Socket_read ($spawn, 1024) or die ("could not read input\n");

The Socker_read parameter is used to specify the number of bytes read, which you can use to limit the size of the data being fetched from the client.

Note: The Socket_read function reads the shell-side data until it meets the \n,\t or the "character." The PHP script regards this character as the input terminator.

8. The server now has to deal with these data sent by the client (in this case the processing only contains the input of the data and uploads back to the client). This can be done by the Socket_write () function (making it possible for a communication socket to send back a data stream to the client)

[Copy to Clipboard]

Processes client input and returns data
$output = Strrev ($input). "\ n";
Socket_write ($spawn, $output, strlen ($output)) or die ("could not write

9. Once the output is returned to the client, the parent/child socket should be terminated by the Socket_close () function

[Copy to Clipboard]

Closure of sockets
Socket_close ($spawn);
Socket_close ($socket); 

The above is the PHP socket communication case detailed, I hope to learn more about socket communication knowledge help.

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.