Table of Contents
TCP/IP Connection
Home Backend Development PHP Tutorial Explain in simple terms: PHP socket communication principle

Explain in simple terms: PHP socket communication principle

Feb 07, 2017 am 10:30 AM

You are not unfamiliar with the words TCP/IP, UDP, and Socket programming, are you? With the development of network technology, these words are flooding our ears. So I want to ask:

1. What are TCP/IP and UDP?

2. Where is the Socket?

3. What is Socket?

4. Can you use them?

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.

Explain in simple terms: PHP socket communication principle

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 let pictures speak for themselves.

Explain in simple terms: PHP socket communication principle

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 meet the specified requirements. protocol.

Will you use them?

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 be done. 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 from life. If you want to call a friend, dial the number first. When the friend hears the ringing tone, he picks up the phone. At this time, you and your friend are connected and you can talk. When the communication is over, hang up the phone to 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.

Explain in simple terms: PHP socket communication principle

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 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 to listen on the specified port

socket_create_pair() Generate a pair of undifferentiated sockets into an array

socket_create() Generate a socket, which is equivalent to generating a socket data structure

socket_get_option() Get the socket option

socket_getpeername() Get 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 capable of sending, receiving, reading and writing

socket_iovec_delete() Delete an already 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 scattered/aggregated array

socket_recv() End the data from the socket to the cache

socket_recvfrom() Accept the data from the specified socket, if not specified, the current socket will be defaulted

socket_recvmsg() Receive messages from iovec

socket_select() Multiple selection

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 with the specified address

socket_set_block() Set 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 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 scattered/aggregated array

Case 1: socket communication demonstration

Server side:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

<?php

//确保在连接客户端时不会超时

set_time_limit(0);

  

$ip = &#39;127.0.0.1&#39;;

$port = 1935;

  

/*

 +-------------------------------

 *  @socket通信整个过程

 +-------------------------------

 *  @socket_create

 *  @socket_bind

 *  @socket_listen

 *  @socket_accept

 *  @socket_read

 *  @socket_write

 *  @socket_close

 +--------------------------------

 */

  

/*----------------  以下操作都是手册上的  -------------------*/

if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {

  echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n";

}

  

if(($ret = socket_bind($sock,$ip,$port)) < 0) {

  echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";

}

  

if(($ret = socket_listen($sock,4)) < 0) {

  echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";

}

  

$count = 0;

  

do {

  if (($msgsock = socket_accept($sock)) < 0) {

    echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";

    break;

  } else {

      

    //发到客户端

    $msg ="测试成功!\n";

    socket_write($msgsock, $msg, strlen($msg));

      

    echo "测试成功了啊\n";

    $buf = socket_read($msgsock,8192);

      

      

    $talkback = "收到的信息:$buf\n";

    echo $talkback;

      

    if(++$count >= 5){

      break;

    };

      

    

  }

  //echo $buf;

  socket_close($msgsock);

  

} while (true);

  

socket_close($sock);

?>

Copy after login

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

Explain in simple terms: PHP socket communication principle

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

and you can see that the port is already in the LISTENING state. Next we only need to run the client program to connect. Upload the code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

<?php

error_reporting(E_ALL);

set_time_limit(0);

echo "<h2 id="TCP-IP-nbsp-Connection">TCP/IP Connection</h2>\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 < 0) {

  echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";

}else {

  echo "OK.\n";

}

  

echo "试图连接 &#39;$ip&#39; 端口 &#39;$port&#39;...\n";

$result = socket_connect($socket, $ip, $port);

if ($result < 0) {

  echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";

}else {

  echo "连接OK\n";

}

  

$in = "Ho\r\n";

$in .= "first blood\r\n";

$out = &#39;&#39;;

  

if(!socket_write($socket, $in, strlen($in))) {

  echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";

}else {

  echo "发送到服务器信息成功!\n";

  echo "发送的内容为:<font color=&#39;red&#39;>$in</font> <br>";

}

  

while($out = socket_read($socket, 8192)) {

  echo "接收服务器回传信息成功!\n";

  echo "接受的内容为:",$out;

}

  

  

echo "关闭SOCKET...\n";

socket_close($socket);

echo "关闭OK\n";

?>

Copy after login

Explain in simple terms: PHP socket communication principle

Explain in simple terms: PHP socket communication principle

The client has now connected to the server.

Case 2: Detailed code explanation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

// 设置一些基本的变量

$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);

Copy after login

The following is a detailed description of each step:

1. The first step is to establish two variables to save the server where the Socket is running. IP address and port. 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.

1

2

3

// 设置两个变量

$host = "192.168.1.99";

$port = 1234;

Copy after login

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.

1

2

// 超时时间

set_time_limit(0);

Copy after login

3. Based on the previous ones, it is time to use socket_creat () function creates a Socket - this function returns a Socket handle, which will be used in all subsequent functions.

1

2

3

// 创建Socket

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create

socket\n");

Copy after login

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 If so, you can use the following code:

1

2

3

// 创建 socket

$socket = socket_create(AF_INET, SOCK_DGRAM, 0) or die("Could not create

socket\n");

Copy after login

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 socket_bind () function to complete.

1

2

3

// 绑定 socket to 指定地址和端口

$result = socket_bind($socket, $host, $port) or die("Could not bind to

socket\n");

Copy after login

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

1

2

3

// 开始监听连接

$result = socket_listen($socket, 3) or die("Could not set up socket

listener\n");

Copy after login

6. Until now, your server does nothing but wait for messages from clients Basically nothing is done except the client's connection request. Once a client connection is received, the socket_accept() function comes into play. It receives the connection request and calls another sub-Socket to handle the client-server information.

1

2

3

4

//接受请求链接

// 调用子socket 处理信息

$spawn = socket_accept($socket) or die("Could not accept incoming

connection\n");

Copy after login

This subsocket can now be used for subsequent client-server communication.

7. When a connection is established, the server will wait for the client The terminal sends some input information. This information can be obtained by the socket_read() function and assigned to the $input variable of PHP.

1

2

// 读取客户端输入

$input = socket_read($spawn, 1024) or die("Could not read input\n");

Copy after login

The second parameter of socker_read is used to Specify the number of bytes to read, you can use it to limit the size of data obtained from the client.

Note: The socket_read function will keep reading the shell client data until it encounters \n, \t or \ 0 characters. The PHP script regards this character as the end of the input.

8. Now the server must process the data sent by the client (in this example, the processing only includes the input and Back to the client). This part can be completed by the socket_write() function (making it possible to send a data stream back to the client through the communication socket)

1

2

3

4

// 处理客户端输入并返回数据

$output = strrev($input) . "\n";

socket_write($spawn, $output, strlen ($output)) or die("Could not write

output\n");

Copy after login

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

1

2

3

// 关闭 sockets

socket_close($spawn);

socket_close($socket);

Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's learning, and I hope Please support PHP Chinese website.

For more in-depth explanations: PHP socket communication principles and related articles, please pay attention to the PHP Chinese website!


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

See all articles