In-depth explanation: PHP socket Communication

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

tcp/ip, udp, socket programming these words, you're not a stranger, are you? With the development of network technology, these words are filled with our ears. So I want to ask:

1.          What is tcp/ip, udp?
2.         socket where?
3.         socket what is it?
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

Server-side:

<?php//Ensure that the client is connected without time-out set_time_limit (0); $ip = ' 127.0.0.1 '; $port = 1935;/* +-------------------------------* @ Socket communication entire process +-------------------------------* @socket_create * @socket_bind * @socket_listen * @socket_accep T * @socket_read * @socket_write * @socket_close +--------------------------------*//*----------------The following actions are Manual-------------------*/if (($sock = Socket_create (af_inet,sock_stream,sol_tcp)) < 0) {echo "Socket_create () failed The reason for this is: ". 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 "

The client is already connected to the service side.

Case two: Code explanation

Set some basic variables $host = "192.168.1.99"; $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 to clipboard]PHP CODE:// 设置两个变量
$host = "192.168.1.99";
$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 to clipboard]PHP CODE:// 超时时间
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 to clipboard]PHP CODE:// 创建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 to clipboard]PHP CODE:// 创建 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 to clipboard]PHP CODE:// 绑定 socket to 指定地址和端口
$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 to clipboard]PHP CODE:// 开始监听连接
$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 to clipboard]PHP CODE://接受请求链接
// 调用子socket 处理信息
$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 to clipboard]PHP CODE:// 读取客户端输入
$input = socket_read($spawn, 1024) or die("Could not read input\n");
?&gt;

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 to clipboard]PHP CODE:// 处理客户端输入并返回数据
$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 to Clipboard]

PHP CODE:

// 关闭 sockets
socket_close($spawn);
socket_close($socket);

In-depth explanation: PHP socket Communication

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.