PHP socket programming _ php Tutorial-PHP Tutorial

Source: Internet
Author: User
PHP socket programming. In-depth introduction to phpsocket programming this article mainly introduces phpsocket programming in a simple way. This article describes socket-related knowledge in detail, PHPsocket programming instance line-based content, and requires in-depth introduction to php socket programming.

This article mainly introduces php socket programming. This article describes socket-related knowledge in detail and PHP socket programming instance installation content. For more information, see

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

1. what are TCP/IP and UDP?

2. where is the Socket?

3. What is Socket?

4. will you use them?

What are TCP/IP and UDP?

TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard Protocol set designed for WANs.

User Data Protocol (UDP) is the Protocol corresponding to TCP. It belongs to the TCP/IP protocol family.

The following figure shows the relationship between these protocols.

TCP/IP protocol families include transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.

Where is the Socket?

In the middle, we didn't see the Socket shadow, so where is it? You can still use graphs to speak clearly.

The original Socket is here.

What is Socket?

Socket is an intermediate software abstraction layer for communications between the application layer and the TCP/IP protocol family. it is a group 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 are all, let the Socket organize the data to conform to the specified protocol.

Will you use them?

Our predecessors have already done a lot for us, and the communication between networks is much simpler, but after all there is still a lot of work to do. I have heard about Socket programming before and think it is a relatively advanced programming knowledge. but as long as I understand the working principle of Socket programming, the mysterious veil will be uncovered.

A scenario in life. You need to call a friend to make a dial-up call. when a friend hears the ringtone and calls the phone, you and your friend can establish a connection to speak. After the communication is over, stop the call. The scenario in life explains this working principle. maybe the TCP/IP protocol family is born in life, which is not necessarily true.

Start with the server. The server first initializes the Socket, then binds it to the port (bind), listens to the port (listen), calls accept, and waits for the client to connect. At this time, if a client initializes a Socket and 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, the response data is sent to the client. the client reads the data and closes the connection. the interaction ends.

Socket-related functions:

Bytes ----------------------------------------------------------------------------------------------

Socket_accept () accepts a Socket connection

Socket_bind () binds the socket to an IP address and port.

Socket_clear_error () clears socket errors or the 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 of identical sockets into an array.

Socket_create () generates a socket, which is equivalent to the data structure of a socket.

Socket_get_option () obtain the socket option

Socket_getpeername () obtains the IP address of a remote host similar to that of a remote host.

Socket_getsockname () gets the IP address of the local socket

Socket_iovec_add () add a new vector to a scattered/aggregated array

Socket_iovec_alloc () this function creates an iovec data structure that can send and receive read/write data.

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 () obtains the final error code of the current socket.

Socket_listen () listens to all connections from the specified socket

Socket_read () reads data of the specified length

Socket_readv () reads data from scattered/aggregate arrays

Socket_recv () ends data from the socket to the cache

Socket_recvfrom () accepts data from the specified socket. If no value is specified, the current socket is used by default.

Socket_recvmsg () receives messages from iovec

Socket_select () multi-path 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 of the specified address

Socket_set_block () is set to block mode in socket

Set the socket in socket_set_nonblock () to non-block mode.

Socket_set_option () sets socket options

The socket_shutdown () function allows you to close the read, write, or specified socket

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

Socket_write () writes data to the socket cache

Socket_writev () writes data to a distributed/aggregate array

Case 1: socket communication demonstration

Server:

?

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 that no timeout occurs when you connect to the client

Set_time_limit (0 );

$ Ip = '1970. 0.0.1 ';

$ Port = 1935;

/*

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

* @ Socket: entire communication process

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

* @ Socket_create

* @ Socket_bind

* @ Socket_listen

* @ Socket_accept

* @ Socket_read

* @ Socket_write

* @ Socket_close

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

*/

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

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

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

}

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

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

}

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

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

}

$ Count = 0;

Do {

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

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 "test succeeded \ n ";

$ Buf = socket_read ($ msgsock, 8192 );

$ Talkback = "received message: $ buf \ n ";

Echo $ talkback;

If (++ $ count> = 5 ){

Break;

};

}

// Echo $ buf;

Socket_close ($ msgsock );

} While (true );

Socket_close ($ sock );

?>

This is the socket server code. Then run cmd. Note the path where your program is stored.

Not Reflected. the current server-side program has started to run and the port has started to listen. Run netstat-ano to check the port status. my port number is Port 1935.

Check that the port is already in the LISTENING status. Next, we only need to run the client program to connect. Code on

?

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 connection process

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

* @ 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 "trying to connect '$ IP' port' $ port'... \ n ";

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

If ($ result <0 ){

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

} Else {

Echo "connect OK \ n ";

}

$ In = "Ho \ r \ n ";

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

$ Out = '';

If (! Socket_write ($ socket, $ in, strlen ($ in ))){

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

} Else {

Echo "sent to server information! \ N ";

Echo "sends the following content: $ in
";

}

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

Echo "received server return message successful! \ N ";

Echo "received content:", $ out;

}

Echo "disable SOCKET... \ n ";

Socket_close ($ socket );

Echo "disable OK \ n ";

?>

Now the client is connected to the server.

Case 2: code details

?

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 the timeout value

Set_time_limit (0 );

// Create a Socket

$ Socket = socket_create (AF_INET, SOCK_STREAM, 0) or die ("cocould not createsocket \ n ");

// Bind the Socket to the port

$ Result = socket_bind ($ socket, $ host, $ port) or die ("cocould not bind tosocket \ n ");

// Start listening link

$ Result = socket_listen ($ socket, 3) or die ("cocould not set up socketlistener \ n ");

// Accept incoming connections

// Another Socket for communication

$ Spawn = socket_accept ($ socket) or die ("cocould not accept incomingconnection \ n ");

// Obtain client input

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

// 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 ("cocould not write

Output \ n ");

// Disable 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 running the Socket. you can set your own server and port (this port can be a number between 1 and 65535), provided that this port is not used.

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 will not time out while waiting for client connection.

The code is as follows:

// Timeout

Set_time_limit (0 );

3. on the basis of the above, we should use the socket_creat () function to create a Socket.-This function returns a Socket handle, which will be used in all future functions.

The code is as follows:

// Create a Socket

$ Socket = socket_create (AF_INET, SOCK_STREAM, 0) or die ("cocould 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)

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

The code is as follows:

// Create a socket

$ Socket = socket_create (AF_INET, SOCK_DGRAM, 0) or die ("cocould 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.

The code is as follows:

// Bind a socket to the specified address and port

$ Result = socket_bind ($ socket, $ host, $ port) or die ("cocould not bind

Socket \ n ");

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

The code is as follows:

// Start listening for connection

$ Result = socket_listen ($ socket, 3) or die ("cocould not set up socket

Listener \ n ");

6. up to now, your server has not done anything except waiting for connection requests from clients. once a client connection is received, the socket_accept () function starts to take effect. it receives connection requests and calls another sub-Socket to process information between clients and servers.

The code is as follows:

// Accept the request link

// Call the sub-socket to process the information

$ Spawn = socket_accept ($ socket) or die ("cocould not accept incoming

Connection \ n ");

This sub-socket can now be used by subsequent client-server communication.

7. after a connection is established, the server will wait for the client to send some input information, which 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 ("cocould not read input \ n ");

?>

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 reads the shell data until \ n, \ t, or \ 0 characters are met. the PHP script regards this write character as an input Terminator.

8. now the server must process the data sent from the client (in this example, only the data is input and returned to the client ). this part can be done by the socket_write () function (making it possible to send a data stream back to the client by the communication socket)

The code is as follows:

// Process client input and return data

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

Socket_write ($ spawn, $ output, strlen ($ output) or die ("cocould not write

Output \ n ");

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:

// Disable sockets

Socket_close ($ spawn );

Socket_close ($ socket );

Sockets socket programming this article mainly introduces php socket programming in a simple way. This article describes socket-related knowledge in detail, PHP socket programming instance line installation content, and what you need...

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.