Home >Backend Development >PHP Tutorial >Detailed explanation of php socket communication_php skills

Detailed explanation of php socket communication_php skills

WBOY
WBOYOriginal
2016-05-16 20:08:371013browse

Are you familiar with the words TCP/IP, UDP, and Socket programming? With the development of network technology, these words are flooding our ears.

So what are TCP/IP and UDP?
TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard protocol set designed for wide area networks (WANs).
UDP (User Data Protocol) is a protocol corresponding to TCP. It is a member of the TCP/IP protocol suite.
Here is a diagram showing the relationship between these protocols.

The TCP/IP protocol suite includes the 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 do not see the shadow of Socket, so where is it? Let’s let pictures speak for themselves.

It turns out that the Socket is here.
What is Socket?
Socket is an intermediate software abstraction layer for communication between the application layer and the TCP/IP protocol family. It is a set of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a set of simple interfaces is all, allowing Socket to organize data to comply with the specified protocol.
Will you use them?
Our predecessors have done a lot for us, and communication between networks has become much simpler, but after all, there is still a lot of work to do. When I heard about Socket programming before, I thought it was relatively advanced programming knowledge, but as long as we understand the working principle of Socket programming, the mystery will be lifted.
A scene in life. If you want to call a friend, dial the number first. After the friend hears the ringing tone, he picks up the phone. At this time, you and your friend are connected and you can talk. Wait until the communication is over, hang up the phone and end the conversation. Scenes in life explain how this works. Maybe the TCP/IP protocol family was born in life, but this is not necessarily the case.

Let’s start with the server side. The server first initializes the Socket, then binds to the port, listens to the port, calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, 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, then sends the response data to the client, the client reads the data, and finally closes the connection, and the interaction ends.

Socket related functions:
-------------------------------------------------- --------------------------------------------------
socket_accept() accepts a Socket connection
socket_bind() binds the socket to an IP address and port
socket_clear_error() clears socket errors or last error code
socket_close() closes a socket resource
socket_connect() starts a socket connection
socket_create_listen() opens a socket listening on the specified port
socket_create_pair() generates a pair of indistinguishable sockets into an array
socket_create() generates a socket, which is equivalent to generating a socket data structure
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() adds a new vector to a scatter/aggregate array
socket_iovec_alloc() This function creates an iovec data structure that can be sent, received, read and written
socket_iovec_delete() deletes an allocated iovec
socket_iovec_fetch() returns the data of the specified iovec resource
socket_iovec_free() releases an iovec resource
socket_iovec_set() sets the new value of iovec data
socket_last_error() gets the last error code of the current socket
socket_listen() listens to all connections from the specified socket
socket_read() reads data of specified length
socket_readv() reads data from the scatter/aggregate array
socket_recv() ends the data from the socket to the cache
socket_recvfrom() accepts data from the specified socket. If not specified, it defaults to the current socket
socket_recvmsg() receives messages from iovec
socket_select() multiple selection
socket_send() This function sends data to the connected socket
socket_sendmsg() sends a message to socket
socket_sendto() sends a message to the socket at the specified address
socket_set_block() sets the socket to block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() sets socket options
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() returns the detailed error with the specified error number
socket_write() writes data to the socket cache
socket_writev() writes data to scatter/aggregate array

Case 1: socket communication demonstration

Server side:

 1 <&#63;php 2 //确保在连接客户端时不会超时 3 set_time_limit(0); 4 5 $ip = '127.0.0.1'; 6 $port = 1935; 7 8 /* 9 +------------------------------- 10 *  @socket通信整个过程 11 +------------------------------- 12 *  @socket_create 13 *  @socket_bind 14 *  @socket_listen 15 *  @socket_accept 16 *  @socket_read 17 *  @socket_write 18 *  @socket_close 19 +-------------------------------- 20 */ 21 22 /*----------------  以下操作都是手册上的  -------------------*/ 23 if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) { 24 echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n"; 25 } 26 27 if(($ret = socket_bind($sock,$ip,$port)) < 0) { 28 echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n"; 29 } 30 31 if(($ret = socket_listen($sock,4)) < 0) { 32 echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n"; 33 } 34 35 $count = 0; 36 37 do { 38 if (($msgsock = socket_accept($sock)) < 0) { 39 echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n"; 40 break; 41 } else { 42 43 //发到客户端 44 $msg ="测试成功!
"; 45 socket_write($msgsock, $msg, strlen($msg)); 46 47 echo "测试成功了啊\n"; 48 $buf = socket_read($msgsock,8192); 49 50 51 $talkback = "收到的信息:$buf\n"; 52 echo $talkback; 53 54 if(++$count >= 5){ 55 break; 56 }; 57 58 59 } 60 //echo $buf; 61 socket_close($msgsock); 62 63 } while (true); 64 65 socket_close($sock); 66 &#63;>

This is the server-side code of the socket. Then run cmd, pay attention to the storage path of your own program.

No response, the server program has started running and the port has started listening. Run netstat -ano to check the port status. Mine is port 1935

Look, the port is already in LISTENING state. Next we only need to run the client program to connect. Up code

 1 <&#63;php 2 error_reporting(E_ALL); 3 set_time_limit(0); 4 echo "<h2>TCP/IP Connection</h2>\n"; 5 6 $port = 1935; 7 $ip = "127.0.0.1"; 8 9 /* 10 +------------------------------- 11 *  @socket连接整个过程 12 +------------------------------- 13 *  @socket_create 14 *  @socket_connect 15 *  @socket_write 16 *  @socket_read 17 *  @socket_close 18 +-------------------------------- 19 */ 20 21 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 22 if ($socket < 0) { 23 echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n"; 24 }else { 25 echo "OK.\n"; 26 } 27 28 echo "试图连接 '$ip' 端口 '$port'...\n"; 29 $result = socket_connect($socket, $ip, $port); 30 if ($result < 0) { 31 echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n"; 32 }else { 33 echo "连接OK\n"; 34 } 35 36 $in = "Ho\r\n"; 37 $in .= "first blood\r\n"; 38 $out = ''; 39 40 if(!socket_write($socket, $in, strlen($in))) { 41 echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n"; 42 }else { 43 echo "发送到服务器信息成功!\n"; 44 echo "发送的内容为:<font color='red'>$in</font> <br>"; 45 } 46 47 while($out = socket_read($socket, 8192)) { 48 echo "接收服务器回传信息成功!\n"; 49 echo "接受的内容为:",$out; 50 } 51 52 53 echo "关闭SOCKET...\n"; 54 socket_close($socket); 55 echo "关闭OK\n"; 56 &#63;>


Now the client has connected to the server.

Case 2: Detailed code explanation

// 设置一些基本的变量
$host = "192.168.1.99";
$port = 1234;
// 设置超时时间
set_time_limit(0);
// 创建一个Socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not createsocket\n");
//绑定Socket到端口
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n");
// 开始监听链接
$result = socket_listen($socket, 3) or die("Could not set up socketlistener\n");
// accept incoming connections
// 另一个Socket来处理通信
$spawn = socket_accept($socket) or die("Could not accept incomingconnection\n");
// 获得客户端的输入
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// 清空输入字符串
$input = trim($input);
//处理客户端输入并返回结果
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write
output\n");
// 关闭sockets
socket_close($spawn);
socket_close($socket);

The following is a detailed description of each step:

1. The first step is to create two variables to save the IP address and port of the server where the Socket is running. You can set it to your own server and port (the port can be a number between 1 and 65535), provided that This port is not in use.

[Copy to clipboard]
PHP CODE:

// 设置两个变量
$host = "192.168.1.99" ;
$port = 1234 ; 

2. You can use the set_time_out() function on the server side to ensure that PHP will not time out while waiting for the client to connect.

[Copy to clipboard]
PHP CODE:

// 超时时间
set_time_limit ( 0 ); 

3. Based on the previous ones, it is time to create a Socket using the socket_creat() function - this function returns a Socket handle, which 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 the domain name;
The second parameter "SOCK_STREM" tells the function what type of Socket will be created (TCP type in this example)

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.一旦创建了一个Socket句柄,下一步就是指定或者绑定它到指定的地址和端口.这可以通过socket_bind()函数来完成.

[Copy to clipboard]
PHP CODE:

// 绑定 socket to 指定地址和端口
$result = socket_bind ( $socket , $host , $port ) or die( "Could not bind to
socket\n" ); 

5.当Socket被创建好并绑定到一个端口后,就可以开始监听外部的连接了.PHP允许你由socket_listen()函数来开始一个监听,同时你可以指定一个数字(在这个例子中就是第二个参数:3)

[Copy to clipboard]
PHP CODE:

// 开始监听连接
$result = socket_listen ( $socket , 3 ) or die( "Could not set up socket
listener\n" ); 

6.到现在,你的服务器除了等待来自客户端的连接请求外基本上什么也没有做.一旦一个客户端的连接被收到,socket_accept()函数便开始起作用了,它接收连接请求并调用另一个子Socket来处理客户端–服务器间的信息.

[Copy to clipboard]
PHP CODE:

//接受请求链接
// 调用子socket 处理信息
$spawn = socket_accept ( $socket ) or die( "Could not accept incoming
connection\n" ); 

这个子socket现在就可以被随后的客户端–服务器通信所用了.

7.当一个连接被建立后,服务器就会等待客户端发送一些输入信息,这写信息可以由socket_read()函数来获得,并把它赋值给PHP的$input变量.

[Copy to clipboard]
PHP CODE:

// 读取客户端输入
$input = socket_read ( $spawn , 1024 ) or die( "Could not read input\n" );
&#63;& gt ; 

socker_read的第而个参数用以指定读入的字节数,你可以通过它来限制从客户端获取数据的大小.

注意:socket_read函数会一直读取壳户端数据,直到遇见\n,\t或者

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn