PHP socket programming in layman's phpsocket_php tutorial

Source: Internet
Author: User
Tags set socket socket connect socket error

In layman's PHP socket programming, in layman Phpsocket

You're not a stranger to TCP/IP, UDP, socket programming. With the development of network technology, these words are filled with our ears. Then I would like to ask:

1. What is TCP/IP, UDP?
Where is 2.Socket?
What is 3.Socket?
4. Will you use them?

What is TCP/IP, UDP?

TCP/IP (transmission Control protocol/internet Protocol) is a protocol/inter-network protocol, an industry-standard set of protocols designed for wide area networks (WANs).

UDP (User data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.

Here is a diagram showing 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's the socket?

In Figure 1, we don't see the socket shadow, so where is it? Or use a diagram to speak, at a glance.

The original socket is here.

What is a socket?

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set 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 communication between the network is a lot simpler, but after all, there is still a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as understand how the socket programming principle, the mysterious veil also opened.
A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. The scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the 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, waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.

Socket correlation function:
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 () Close a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () Open a socket listener on the specified port
Socket_create_pair () produces a pair of indistinguishable sockets into an array
Socket_create () produces a socket equivalent to a data structure that produces a socket
Socket_get_option () Get socket options
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write
Socket_iovec_delete () Delete an already assigned Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () releasing a Iovec resource
Socket_iovec_set () Sets the new data value of the Iovec
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 from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket
Socket_recvmsg () receive messages from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends the 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 () set as block mode in socket
Socket_set_nonblock () set to non-block mode in socket
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


<?php//Ensure that the client is connected without time-out set_time_limit (0); $ip = ' '; $port = 1935;/* +-------------------------------* @ Socket communication entire process +-------------------------------* @socket_create * @socket_bind * @socket_listen * @socket_accept * @so Cket_read * @socket_write * @socket_close +--------------------------------*//*----------------The following actions are on the manual---------- ---------*/if (($sock = Socket_create (af_inet,sock_stream,sol_tcp)) < 0) {echo "Socket_create () failed due to:". socket_ Strerror ($sock). " \ n ";} if ($ret = Socket_bind ($sock, $ip, $port)) < 0) {echo "Socket_bind () failed due to:". Socket_strerror ($ret). " \ n ";} if ($ret = Socket_listen ($sock, 4)) < 0) {echo "Socket_listen () failed due to:". Socket_strerror ($ret). " \ n ";} $count = 0;do {if ($msgsock = socket_accept ($sock)) < 0) {echo "socket_accept () Failed:reason:". Socket_strerror ($msgsock).    "\ n";  Break } else {//sent to client $msg = "Test succeeded!    \ n ";        Socket_write ($msgsock, $msg, strlen ($msg));    echo "The test was successful AH \ n"; $buf = Socket_read ($msgsock, 8192);    $talkback = "Info received: $BUF \ n";        Echo $talkback;    if (+ + $count >= 5) {break;        };  }//echo $buf; Socket_close ($msgsock);} while (true); Socket_close ($sock);? >

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

No reflection, the current service side of the program has started to run, the port has started to listen. Run Netstat-ano to see the port condition, mine is port 1935.

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

<?phperror_reporting (E_all); set_time_limit (0); echo "

TCP/IP Connection

\ n "; $port = 1935; $ip =" ";/* +-------------------------------* @socket connect the whole process +------------------------------ -* @socket_create * @socket_connect * @socket_write * @socket_read * @socket_close +-------------------------------- */$socket = Socket_create (Af_inet, Sock_stream, sol_tcp), if ($socket < 0) {echo "socket_create () Failed:reason:". Socket_strerror ($socket). "\ n";} else {echo "ok.\n";} echo "Attempted to connect ' $ip ' port ' $port ' ... \ n"; $result = Socket_connect ($socket, $ip, $port); if ($result < 0) {echo "Socket_connec T () Failed.\nreason: ($result) ". Socket_strerror ($result). "\ n";} else {echo "Connect ok\n";} $in = "ho\r\n"; $in. = "First blood\r\n"; $out = "; if (!socket_write ($socket, $in, strlen ($in))) {echo" Socket_write () FAI Led:reason: ". Socket_strerror ($socket). "\ n";} else {echo "sent to server information successfully! \ n "; echo "sends the content as: $in
";} while ($out = Socket_read ($socket, 8192)) {echo "Receives server backhaul information successfully! \ n "; echo "accepts the content as:", $out;} echo "Close socket...\n"; Socket_close ($socket); echo "Close ok\n";? >

The client is already connected to the service side.

Case two: Code explanation

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 ("Cou LD not bind tosocket\n ");//start monitoring link $result = Socket_listen ($socket, 3) or Die (" Could not set up socketlistener\n ");//Accep T incoming connections//another socket to handle communication $spawn = Socket_accept ($socket) or Die ("Could not accept incomingconnection\n"); /Get client input $input = Socket_read ($spawn, 1024x768) or Die ("Could not read input\n");//Empty input string $input = Trim ($input);//process client input and return Result $output = Strrev ($input). "\ n"; Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not writeoutput\n");//Close Socketssocket_close ($spawn ); Socket_close ($socket);

The following is a detailed description of each of these 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 up your own server and port (this port can be a number from 1 to 65535), provided that the port is not in use.
Copy the Code code as follows:
Set two variables
$host = "";
$port = 1234;

2. The Set_time_out () function can be used on the server side to ensure that PHP does not time out while waiting for the client to connect.

Copy the Code code as follows:
Timeout period
Set_time_limit (0);

3. On the previous basis, it is now 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 the Code code as follows:
Create socket
$socket = Socket_create (af_inet, sock_stream, 0) or die ("Could not create
Socket\n ");

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

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

Copy the Code code as follows:
Create socket
$socket = Socket_create (af_inet, SOCK_DGRAM, 0) or die ("Could not create
Socket\n ");

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 the Code code as follows:
Bind socket to specify address and port
$result = Socket_bind ($socket, $host, $port) or Die ("Could not bind to
Socket\n ");

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 the Code code as follows:
Start listening for connections
$result = Socket_listen ($socket, 3) or Die ("Could not set up socket
Listener\n ");

6. Until now, your server has done nothing but wait for a connection request from the client. Once a client's connection is received, the socket_accept () function begins to work, receiving a connection request and invoking another child socket to process the client-server information.

Copy the Code code as follows:
Accept Request Link
Calling Child socket processing information
$spawn = socket_accept ($socket) or Die ("Could not accept incoming
Connection\n ");

This sub-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 assign it to the PHP $input variable.
Copy the Code code as follows:
Read Client input
$input = Socket_read ($spawn, 1024x768) or Die ("Could not read input\n");

The first parameter of the Socker_read specifies the number of bytes to read, which you can use to limit the size of the data that is fetched from the client.

Note: The Socket_read function will always read the shell data until it encounters the \n,\t or the/s character. The PHP script considers this character to be the input terminator.

8. The server must now handle these data sent by the client (in this case the processing only contains data input and is uploaded to the client). This can be done by the Socket_write () function (which makes it possible to send a data stream back to the client by a communication socket)

Copy the Code code as follows:
Process client input and return data
$output = Strrev ($input). "\ n";
Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not write
Output\n ");

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

Copy the Code code as follows:
Close sockets
Socket_close ($spawn);
Socket_close ($socket); true techarticle In -depth PHP socket programming, in layman phpsocket TCP/IP, UDP, socket programming These words you will not be very strange? With the development of network technology, these words are filled with our ears. ...

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