search
HomeBackend DevelopmentPHP TutorialAn in-depth explanation of php socket programming_PHP tutorial

Introduction to PHP socket programming in a simple and easy way

This article mainly introduces PHP socket programming in an easy-to-understand way. This article explains in detail the relevant knowledge of sockets and the packaging content of PHP socket programming examples. What is needed Friends can refer to it

You are familiar with the words TCP/IP, UDP, and Socket programming, right? With the development of network technology, these words are filling our ears. Then 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.

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 don’t see the shadow of Socket, so where is it? Let’s use the picture to speak, it’s clear at a glance.

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.

Can you use them?

Previous generations 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.

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 the socket error or the 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() Gets 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() Set the socket to block mode

 socket_set_nonblock() Set the socket to non-block mode

 socket_set_option() Set socket options

Socket_shutdown() This function allows you to close reading, writing, or the specified socket

Socket_strerror() returns the detailed error of the specified error number

Socket_write() writes data to the socket cache

 socket_writev() writes data to the scatter/aggregate 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

// Ensure there is no timeout when connecting to the client

set_time_limit(0);

$ip = '127.0.0.1';

$port = 1935;

/*

----------------------------------

* The whole process of @socket communication

----------------------------------

* @socket_create

* @socket_bind

* @socket_listen

* @socket_accept

* @socket_read

* @socket_write

* @socket_close

--------------------------------

*/

/*----------------The following operations are in the manual------------------*/

if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP))

echo "socket_create() failed because: ".socket_strerror($sock)."n";

}

if(($ret = socket_bind($sock,$ip,$port))

echo "socket_bind() failed because: ".socket_strerror($ret)."n";

}

if(($ret = socket_listen($sock,4))

echo "socket_listen() failed because: ".socket_strerror($ret)."n";

}

$count = 0;

do {

if (($msgsock = socket_accept($sock))

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

break;

} else {

//Send to client

$msg="Test successful!n";

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

echo "The test was successful";

$buf = socket_read($msgsock,8192);

$talkback = "Message received: $bufn";

echo $talkback;

if( $count >= 5){

break;

};

 

 

}

//echo $buf;

socket_close($msgsock);

 

} while (true);

 

socket_close($sock);

?>

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

There is no reflection. 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

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

error_reporting(E_ALL);

set_time_limit(0);

echo "

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

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

}else {

echo "OK.n";

}

 

echo "试图连接 '$ip' 端口 '$port'...n";

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

if ($result

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

}else {

echo "连接OKn";

}

 

$in = "Horn";

$in .= "first bloodrn";

$out = '';

 

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

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

}else {

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

echo "发送的内容为:$in
";

}

 

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

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

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

}

 

 

echo "关闭SOCKET...n";

socket_close($socket);

echo "关闭OKn";

?>

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
error_reporting(E_ALL); set_time_limit(0); echo "

TCP/IP Connection

n"; $port = 1935; $ip = "127.0.0.1"; /* ---------------------------------- * @socket connects the entire process ---------------------------------- * @socket_create * @socket_connect * @socket_write * @socket_read * @socket_close -------------------------------- */ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket echo "socket_create() failed: reason: " . socket_strerror($socket) . "n"; }else { echo "OK.n"; } echo "Trying to connect to '$ip' port '$port'...n"; $result = socket_connect($socket, $ip, $port); if ($result echo "socket_connect() failed.nReason: ($result) " . socket_strerror($result) . "n"; }else { echo "Connect OKn"; } $in = "Horn"; $in .= "first bloodrn"; $out = ''; if(!socket_write($socket, $in, strlen($in))) { echo "socket_write() failed: reason: " . socket_strerror($socket) . "n"; }else { echo "Information sent to server successfully!n"; echo "The content sent is:$in
"; } while($out = socket_read($socket, 8192)) { echo "Receiving server response information successfully!n"; echo "The accepted content is:",$out; } echo "Close SOCKET...n"; socket_close($socket); echo "Close OKn"; ?>

Now the client has 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 createsocketn");

//绑定Socket到端口

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

// 开始监听链接

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

// accept incoming connections

// 另一个Socket来处理通信

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

// 获得客户端的输入

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

// 清空输入字符串

$input = trim($input);

//处理客户端输入并返回结果

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

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

outputn");

// 关闭sockets

socket_close($spawn);

socket_close($socket);

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
//Set some basic variables $host = "192.168.1.99"; $port = 1234; //Set timeout set_time_limit(0); //Create a Socket $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not createocketn"); //Bind Socket to port $result = socket_bind($socket, $host, $port) or die("Could not bind tosocketn"); // Start monitoring the link $result = socket_listen($socket, 3) or die("Could not set up socketlistenern"); // accept incoming connections //Another Socket to handle communication $spawn = socket_accept($socket) or die("Could not accept incomingconnectionn"); // Get input from the client $input = socket_read($spawn, 1024) or die("Could not read inputn"); //Clear the input string $input = trim($input); //Process client input and return results $output = strrev($input) . "n"; socket_write($spawn, $output, strlen ($output)) or die("Could not write outputn"); //Close 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.

The code is as follows:

// Set two variables

 $host = "192.168.1.99";

 $port = 1234;

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

The code is as follows:

// Timeout

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.

The code is as follows:

// Create Socket

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

socketn");

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)

Therefore, if you want to create a UDP Socket, you can use the following code:

The code is as follows:

// Create socket

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

socketn");

 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.

The code is as follows:

// Bind socket to specified address and port

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

socketn");

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

The code is as follows:

// Start monitoring connections

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

Listenern");

6. Up to now, your server has basically done nothing except waiting for the connection request from the client. Once a client connection is received, the socket_accept() function comes into play. It receives the connection request and Call another sub-Socket to handle information between client and server.

The code is as follows:

//Accept request link

// Call subsocket to process information

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

 connectionn");

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

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

The code is as follows:

// Read client input

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

 ?>

The second parameter of socker_read is used to specify the number of bytes to be 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

8. Now the server must process the data sent by the client (in this example, the processing only includes the input and return of data to the client). This part can be completed by the socket_write() function (so that by It is possible for the communication socket to send back a data stream to the client)

The code is as follows:

// Process client input and return data

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

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

outputn");

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

The code is as follows:

// Close sockets

socket_close($spawn);

 socket_close($socket);

http://www.bkjia.com/PHPjc/1000097.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1000097.htmlTechArticleIntroduction to PHP socket programming in a simple way This article mainly introduces PHP socket programming in an easy way. This article explains socket-related knowledge in detail , PHP socket programming example package content, need friends...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.