_php Tutorial for PHP socket programming

Source: Internet
Author: User
Tags set socket socket connect socket error

PHP socket programming in layman's language


This article mainly introduces the in-depth PHP socket programming, this article explains the socket of the relevant knowledge, PHP socket Programming example of the contents of the pack, the need for friends can refer to the next

For TCP/IP, UDP, socket programming These words, you're not a stranger, are you? With the development of network technology, these words are filled with our ears. Then I would like to ask:

1. What is TCP/IP, UDP?

Where is 2.Socket?

What is 3.Socket?

4. Will you use them?

What is TCP/IP, UDP?

TCP/IP (transmission Control protocol/internet Protocol) is a protocol/inter-network protocol, an industry-standard set of protocols designed for wide area networks (WANs).

UDP (User data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.

Here is a diagram showing the relationship of these protocols.

The TCP/IP protocol family includes transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.

Where's the socket?

In Figure 1, we don't see the shadow of the socket, so where is it? or use a diagram to speak, at a glance.

The original socket is here.

What is a socket?

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

Will you use them?

Predecessors have done a lot of things to us, the communication between the network is a lot simpler, but after all, there is still a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as understand how the socket programming principle, the mysterious veil also opened.

A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. The scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the life, this is not necessarily.

Start with the server side. The server-side initializes the socket, then binds to the port (BIND), listens to the port (listen), calls the Accept block, waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.

Socket correlation Function:

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

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 () Close a socket resource

Socket_connect () Start a socket connection

Socket_create_listen () Open a socket listener on the specified port

Socket_create_pair () produces a pair of indistinguishable sockets into an array

Socket_create () produces a socket equivalent to a data structure that produces a socket

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 () Add a new vector to a scatter/aggregate array

Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write

Socket_iovec_delete () Delete an already assigned Iovec

Socket_iovec_fetch () returns the data for the specified Iovec resource

Socket_iovec_free () releasing a Iovec resource

Socket_iovec_set () Sets the new data value of the Iovec

Socket_last_error () Gets the last error code for the current socket

Socket_listen () listens for all connections by the specified socket

Socket_read () reads the specified length of data

SOCKET_READV () reads data from a scatter/aggregate array

SOCKET_RECV () end data from socket to cache

Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket

Socket_recvmsg () receive messages from Iovec

Socket_select () multi-channel selection

Socket_send () This function sends the data to the connected socket

SOCKET_SENDMSG () Send message to socket

Socket_sendto () sends a message to the socket at the specified address

Socket_set_block () set as block mode in socket

Socket_set_nonblock () set to non-block mode in socket

Socket_set_option () Set socket options

Socket_shutdown () This function allows you to close a read, write, or specified socket

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

Socket_write () write data to the socket cache

Socket_writev () write data to a scatter/aggregate array

Case ONE: Socket communication Demo

Server-side:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

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 the client is not timed out when connecting

Set_time_limit (0);

$ip = ' 127.0.0.1 ';

$port = 1935;

/*

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

* @socket the entire process of communication

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

* @socket_create

* @socket_bind

* @socket_listen

* @socket_accept

* @socket_read

* @socket_write

* @socket_close

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

*/

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

if ($sock = Socket_create (af_inet,sock_stream,sol_tcp)) < 0) {

The reason for the echo "socket_create () failure is:". Socket_strerror ($sock). " \ n ";

}

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

The reason for the echo "Socket_bind () failure is:". Socket_strerror ($ret). " \ n ";

}

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

The reason for the echo "Socket_listen () failure is:". 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 succeeded! \ n ";

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

echo "The test was successful AH \ n";

$buf = Socket_read ($msgsock, 8192);

$talkback = "Info received: $BUF \ n";

Echo $talkback;

if (+ + $count >= 5) {

Break

};

}

Echo $buf;

Socket_close ($msgsock);

} while (true);

Socket_close ($sock);

?>

This is the server-side code for the socket. Then run CMD, note that it is your own program to store the path AH.

No reflection, the current service side of the program has started to run, the port has started to listen. Run Netstat-ano to see the port condition, mine is port 1935.

Look, the port is already in the listening state. Next we just run the client program to connect. On the Code

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

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 connect the whole 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 "Attempted 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 successfully! \ n ";

echo "sends the content as: $in
";

}

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

echo "Receive server backhaul information successfully! \ n ";

echo "accepts the content as:", $out;

}

echo "Off socket...\n";

Socket_close ($socket);

echo "Off ok\n";

?>

The client is already connected to the service side.

Case two: Code explanation

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

Set some basic variables

$host = "192.168.1.99";

$port = 1234;

Setting the time-out period

Set_time_limit (0);

Create a socket

$socket = Socket_create (af_inet, sock_stream, 0) or die ("Could not createsocket\n");

Bind socket to Port

$result = Socket_bind ($socket, $host, $port) or Die ("Could not bind tosocket\n");

Start listening links

$result = Socket_listen ($socket, 3) or Die ("Could not set up socketlistener\n");

Accept Incoming Connections

Another socket to handle communication

$spawn = socket_accept ($socket) or Die ("Could not accept incomingconnection\n");

Get input from the client

$input = Socket_read ($spawn, 1024x768) or Die ("Could not read input\n");

Empty the input string

$input = Trim ($input);

Processing client input and returning results

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

Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not write

Output\n ");

Close sockets

Socket_close ($spawn);

Socket_close ($socket);

The following is a detailed description of each of these steps:

1. The first step is to create two variables to hold the IP address and port of the server on which the socket is running. You can set up your own server and port (this port can be a number from 1 to 65535), provided that the port is not in use.

The code is as follows:

Set two variables

$host = "192.168.1.99";

$port = 1234;

2. The Set_time_out () function can be used 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 period

Set_time_limit (0);

3. On the previous basis, it is now time to use the Socket_creat () function to create a socket-this function returns a socket handle that 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

Socket\n ");

The first parameter "Af_inet" is used to specify a domain name;

The second argument "Sock_strem" tells the function what type of socket to create (in this case TCP type)

So, 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

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 socket to specify address and port

$result = Socket_bind ($socket, $host, $port) or Die ("Could not bind to

Socket\n ");

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

The code is as follows:

Start listening for connections

$result = Socket_listen ($socket, 3) or Die ("Could not set up socket

Listener\n ");

6. Until now, your server has done nothing but wait for a connection request from the client. Once a client's connection is received, the socket_accept () function begins to work, receiving a connection request and invoking another child socket to process the client-server information.

The code is as follows:

Accept Request Link

Calling Child socket processing information

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

Connection\n ");

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

7. When a connection is established, the server waits for the client to send some input information, which can be obtained by the Socket_read () function and assign it to the PHP $input variable.

The code is as follows:

Read Client input

$input = Socket_read ($spawn, 1024x768) or Die ("Could not read input\n");

?>

The first parameter of the Socker_read specifies the number of bytes to read, which you can use to limit the size of the data that is fetched from the client.

Note: The Socket_read function will always read the shell data until it encounters the \n,\t or the/s character. The PHP script considers this character to be the input terminator.

8. The server must now handle these data sent by the client (in this case the processing only contains data input and is uploaded to the client). This can be done by the Socket_write () function (which makes it possible to send a data stream back to the client by a 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 ("Could not write

Output\n ");

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

The code is as follows:

Close sockets

Socket_close ($spawn);

Socket_close ($socket);

http://www.bkjia.com/PHPjc/1000097.html www.bkjia.com true http://www.bkjia.com/PHPjc/1000097.html techarticle in-depth PHP socket programming This article mainly introduces the understanding of PHP socket programming, this article explains the socket of the relevant knowledge, PHP socket Programming example of the contents of the packing, need friends ...

  • Related Article

    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.