Home  >  Article  >  Backend Development  >  PHP socket communication content

PHP socket communication content

不言
不言Original
2018-04-23 10:12:351092browse

This article mainly introduces the socket communication of PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

What are TCP/IP and UDP?


TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard protocol set for wide area networks (WANs) Designed.
UDP (User Data Protocol, User Datagram Protocol) is the protocol corresponding to TCP. It is a member of the TCP/IP protocol suite.
Here is a diagram showing the relationship between these protocols.
PHP socket communication content
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 Socket?
In Figure 1, we do not see the shadow of Socket, so where is it? Let’s use pictures to speak clearly.
PHP socket communication content

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 meet the specified requirements. protocol.
Working principle
PHP socket communication content
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() Accept a Socket connection
socket_bind() Bind the socket to an IP address and port
socket_clear_error() Clear Socket error or final error code
socket_close() Closes a socket resource
socket_connect() Starts a socket connection
socket_create_listen() Opens a socket listener on the specified port
socket_create_pair() Generates a pair Put the undifferentiated socket into an array
socket_create() generates a socket, which is equivalent to generating a socket data structure
socket_get_option() Gets the socket option
socket_getpeername() Gets the IP address of a remote similar host
socket_getsockname() Get 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 an iovec data structure that can send, receive, read and write
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() Get the last error code of the current socket
socket_listen() Listen to all connections from the specified socket
socket_read() Read the data of the specified length
socket_readv() Read the data from the scatter/aggregate array
socket_recv() End data from the socket to the cache
socket_recvfrom() Accept data from the specified socket, if not specified, the current socket will be defaulted
socket_recvmsg() Receive messages from iovec
socket_select() Multiple channels Select
socket_send() This function sends data to the connected socket
socket_sendmsg() Sends a message to the socket
socket_sendto() Sends a message to the socket of the specified address
socket_set_block() Set it in the socket to Block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() Set the socket option
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() Return Detailed error of specified error number
socket_write() Write data to socket cache
socket_writev() Write data to scatter/aggregate array

Case: socket communication demonstration

Server side:

= 5){
            break;
        };
        
    
    }
    //echo $buf;
    socket_close($msgsock);

} while (true);

socket_close($sock);
?>

Save and execute this file. Run netstat -ano to check the port status. Mine is port 1935.
The port is LISTENING, which means it is already listening. Next we only need to run the client program to connect.
Client:

TCP/IP Connection\n";

$port = 1935;
$ip = "127.0.0.1";

/*
 +-------------------------------
 *    @socket连接整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 */

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket $in 
"; } while($out = socket_read($socket, 8192)) {     echo "接收服务器回传信息成功!\n";     echo "接受的内容为:",$out; } echo "关闭SOCKET...\n"; socket_close($socket); echo "关闭OK\n"; ?>

Execute the server and return information to the client. At this point, the client has connected to the server

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 (this port can be a number between 1 and 65535), provided that this port is not in use.

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

2.在服务器端可以使用set_time_out()函数来确保PHP在等待客户端连接时不会超时.

// 超时时间
set_time_limit(0);

3.在前面的基础上,现在该使用socket_creat()函数创建一个Socket了—这个函数返回一个Socket句柄,这个句柄将用在以后所有的函数中.

// 创建Socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

第一个参数”AF_INET”用来指定域名;
第二个参数”SOCK_STREM”告诉函数将创建一个什么类型的Socket(在这个例子中是TCP类型)

因此,如果你想创建一个UDP Socket的话,你可以使用如下的代码:

// 创建 socket
$socket = socket_create(AF_INET, SOCK_DGRAM, 0) or die("Could not create socket\n");

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

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

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

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

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

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

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

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

socker_read的第而个参数用以指定读入的字节数,你可以通过它来限制从客户端获取数据的大小.
注意:socket_read函数会一直读取壳户端数据,直到遇见n,t或者0字符.PHP脚本把这写字符看做是输入的结束符.
8.现在服务器必须处理这些由客户端发来是数据(在这个例子中的处理仅仅包含数据的输入和回传到客户端).这部分可以由socket_write()函数来完成(使得由通信socket发回一个数据流到客户端成为可能)

// 处理客户端输入并返回数据
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");

9.一旦输出被返回到客户端,父/子socket都应通过socket_close()函数来终止

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

相关推荐:

php实现socket的方法 

PHP之Socket服务器搭建和测试实例分享

The above is the detailed content of PHP socket communication content. For more information, please follow other related articles on the PHP Chinese website!

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