Phpsocket and examples

Source: Internet
Author: User
Tags ping and traceroute
In this chapter, you will understand the fascinating and confusing socket (Sockets), which is not fully utilized in PHP, today, you will see a server that can be connected using a client, and connect using a socket on the client... in this chapter, you will understand the fascinating and confusing socket (Sockets), which is not fully utilized in PHP, today, you will see a server that can connect to the client and connect to the client using socket. the server sends detailed processing information to the client.

When you see the complete socket process, you will use it in future program development. This server is an HTTP server that allows you to connect to, and the client is a Web browser, which is a single client/server relationship.

Socket basics

PHP uses the Berkley socket library to create its connection. You can know that socket is just a data structure. You use this socket data structure to start a session between the client and the server. This server is listening for preparing to generate a new session. When a client connects to the server, it opens a port on which the server is listening for a session. At this time, the server accepts the client connection request, then a loop is performed. Now the client can send information to the server, and the server can also send information to the client.

To generate a Socket, you need three variables: one protocol, one socket type, and one public protocol type. to generate a socket, three protocols are available, continue to read the following content to obtain detailed protocol content.

Defining a public protocol type is an essential element for connection. The following table shows the common protocol types.

Table 1: Protocols

Name/constant description

AF_INET: this is the majority of protocols used to generate sockets. it is transmitted over TCP or UDP and used for IPv4 addresses.

AF_INET6 is similar to the above, but it is used for IPv6 addresses.

The AF_UNIX local protocol is rarely used on Unix and Linux systems. it is generally used when the client and server are on the same server and on the same server.

Table 2: Socket type

Name/constant description

SOCK_STREAM is a sequential, reliable, and complete byte stream-based connection. This is the most widely used socket type, which is transmitted over TCP.

SOCK_DGRAM is a connectionless and fixed-length transmission call. The protocol is unreliable and UDP is used for its connection.

SOCK_SEQPACKET is a dual-line, reliable connection that sends fixed-length data packets for transmission. This package must be fully accepted before it can be read.

The socket type SOCK_RAW provides a single network access, which uses the ICMP public protocol. (Ping and traceroute use this protocol)

SOCK_RDM is rarely used and is not implemented in most operating systems. it is provided to the data link layer and does not guarantee the data packet sequence.

Table 3: public protocols

Name/constant description

The ICMP Internet Control Message Protocol is mainly used on gateways and hosts to check network conditions and report error messages.

UDP user data packet protocol, which is a connectionless and unreliable transmission protocol

TCP transmission control protocol, which is the most reliable public protocol, ensures that the data packet can reach the receiver. If an error occurs during transmission, it resends the error data packet.

Now that you know the three elements that generate a socket, we will use the socket_create () function in php to generate a socket. The socket_create () function requires three parameters: one protocol, one socket type, and one public protocol. If the socket_create () function runs successfully, a resource type containing socket is returned. if the function fails, false is returned.

Resourece socket_create (int protocol, int socketType, int commonProtocol );

Now you generate a socket. what then? Php provides several functions to manipulate the socket. You can bind a socket to an IP address, listen to the communication of a socket, and accept a socket. now let's look at an example to learn how the function generates, accepts, and listens to a socket.

 

The above example generates your own server. The first line of the example,

$ CommonProtocol = getprotobyname ("tcp ");

Use the public protocol name to obtain a protocol type. TCP public protocol is used here. if you want to use UDP or ICMP, you should change the parameter of the getprotobyname () function to "udp" or "icmp ". Another option is to specify SOL_TCP or SOL_UDP in the socket_create () function instead of using the getprotobyname () function.

$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP );

The second line of the example is the instance that generates a socket and returns a socket resource. After you have an instance with a socket resource, you must bind the socket to an IP address and a port.

Socket_bind ($ socket, 'localhost', 1337 );

Here you bind the socket to the local computer (127.0.0.1) and bind the socket to your port 1337. Then you need to listen to all incoming socket connections.

Socket_listen ($ socket );

After the fourth line, you need to understand all socket functions and their usage.

Table 4: Socket functions

Function name description

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

(Note: The function introduction deletes some of the original content. For more information about function usage, see the original English text or the PHP manual)

All the above functions are about socket in PHP. to use these functions, you must open your socket. if you do not open it, edit your php. ini file, remove the comments before the following line:

Extension = php_sockets.dll

If you cannot remove the annotation, use the following code to load the extension Library:

 

If you do not know whether your socket is enabled, you can use the phpinfo () function to determine whether the socket is enabled. You can check the phpinfo information to see whether the socket is opened and the phpinfo () information about the socket.

Generate a server

Now let's complete the first example. You need to listen to a specified socket and process user connections.

 

You should use your command prompt to run this example. The reason is that a server is generated, not a Web page. If you try to use a Web browser to run this script, it is likely to exceed 30 seconds. You can use the following code to set an unlimited running time, but we recommend that you use a command prompt to run it.

Set_time_limit (0 );

Perform a simple test on the script in your command prompt: Php.exe example01_server.php

If you have not set the PHP interpreter in the system environment variable, you can specify the detailed path for php.exe. When you run this server, you can connect to port 1337 through remote login (telnet) to test this server.

The preceding server has three problems: 1. it cannot accept multiple connections. 2. it only completes a unique command. 3. you cannot connect to this server through a Web browser.

This first problem is easy to solve. you can use an application to connect to the server every time. However, the problem is that you need to use a Web page to connect to the server, which is more difficult. You can make your server accept the connection, and then send some data to the client (if it must be written), close the connection and wait for the next connection, and make improvements based on the previous code, generate the following code for your new server:

 

What does this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection. Once a connection is generated, it prints "Socket connected" on the server screen. This server checks the buffer zone. if there is data in the buffer zone, it sends the data to the connected computer. Then, it sends the receiving information of the data. once it accepts the information, it stores the information in the data, allows the connected computer to know the information, and closes the connection. When the connection is closed, the server starts to process the next connection.

Generate a client

It is easy to handle the second problem. You need to generate a php page to connect to a socket, send some data to its cache, and process it. Then you have another processed data, and you can send your data to the server. Connect to another client and it will process the data.

The following example demonstrates the use of socket:

 NO DATA

"); break; } else { // Do something with the data in the buffer echo ("

Buffer Data: " . $buffer . "

"); }}echo ("

Writing to Socket

");// Write some test data to our socketif (!socket_write($socket, "SOME DATArn")) { echo ("

Write failed

");}// Read any response from the socketwhile ($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)) { echo ("

Data sent was: SOME DATA
Response was:" . $buffer . "

");}echo ("

Done Reading from Socket

");?>

The code in this example demonstrates how to connect the client to the server. The client reads data. If this is the first connection to reach this loop, the server will send "no data" back to the client. If this happens, the client is connected. The client sends its data to the server, and the data is sent to the server. the client waits for a response. Once the response is received, it will write the response to the screen, combined with the Socket tank war, because it describes the combination of the game and socket, it is not very relevant to this article, so it is not translated, we recommend that you refer to the original English document.

Digress:The original intention of the translation article is that I am personally very interested in socket, and currently there are few articles in php in China, except for some of the content in the php Manual, so after I read the socket content in the book "PHP Game Programming", I decided to translate the content. I know that the quality of the translation is not good. please forgive me.

In addition, I also found that the Socket content in Core PHP Programming Third Edition is good. if I have time, I think I may also translate it. This is the first time I have translated an article. it took me nearly five hours to translate it. it may be a hundred errors. if the translation is unreasonable, please forgive me. if you are interested in improving this content, please send me an email. In the early hours of the morning, I was unable to sleep. I don't know if I was in another corner, and some people were like me.

I hope this article will help you with PHP Socket programming. thank you for reading this article.


Tutorial link:

Reprint at will ~ However, please keep the tutorial address★

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.