Home > php教程 > PHP开发 > body text

php Socket basics

黄舟
Release: 2016-12-17 10:30:42
Original
1156 people have browsed it

◆ Socket Basics
php uses Berkley's socket library to create its connection. A socket is nothing more than a data structure. You use this socket data structure to start a session between the client and the server. This server is always listening and 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's connection request and then performs a cycle. Now the client can send information to the server, and the server can send information to the client.
To generate a Socket, you need three variables: a protocol, a socket type and a public protocol type. There are three protocols to choose from when generating a socket. Continue reading below to get detailed protocol content.
Defining a public protocol type is an essential element for connection. In the table below we take a look at the common protocol types.
Table 1: Protocol
Name/Constant Description
AF_INET This is most of the protocols used to generate sockets, using TCP or UDP for transmission, and used in ipv4 addresses
AF_INET6 Similar to the above, but used in IPv6 addresses
AF_UNIX local protocol, used on Unix and Linux systems. It is rarely used. It is usually used when the client and server are on the same machine.
Table 2: Socket type
Name/Constant Description
SOCK_STREAM This protocol is based on Sequential, reliable, data-integrated byte stream-based connections. This is the most commonly used socket type. This socket uses TCP for transmission.
SOCK_DGRAM This protocol is a connectionless, fixed-length transfer call. This protocol is unreliable and uses UDP for its connections.
SOCK_SEQPACKET This protocol is a dual-line, reliable connection that sends fixed-length data packets for transmission. This package must be accepted completely before it can be read.
SOCK_RAW This socket type provides single network access. This socket type uses the ICMP public protocol. (ping and traceroute use this protocol)
SOCK_RDM This type is rarely used and is not implemented on most operating systems. It is provided to the data link layer and does not guarantee the order of data packets
Table 3: Public protocols
Name/Constant Description
ICMP Internet Control Message Protocol, mainly used on gateways and hosts to check network conditions and report error messages
UDP User Datagram Protocol, it is a connectionless, unreliable transmission protocol
TCP transmission Control protocol, which is the most commonly used reliable public protocol, can ensure that the data packet can reach the recipient. If an error occurs during the transmission process, it will resend the error packet.
Now that you know the three elements to generate a socket, we use the socket_create() function in php to generate a socket. This socket_create() function requires three parameters: a protocol, a socket type, and a public protocol. The socket_create() function returns a resource type containing the socket if it succeeds, or false if it fails.
Resourece socket_create(int PRotocol, int socketType, int commonProtocol);
Now you generate a socket, then what? PHP provides several functions for manipulating sockets. You can bind a socket to an IP, listen to a socket's communication, and accept a socket; now let's look at an example to understand how the function generates, accepts, and listens to a socket.
$commonProtocol = getprotobyname("tcp");//Use the public protocol name to get a protocol type
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);//Generate a socket and return a socket Resource instance
socket_bind($socket, 'localhost', 1337);//Bind the socket to the local computer
socket_listen($socket);//Listen to all incoming socket connections
// More socket functionality to come
?> ;
The above example generates your own server side. The first line of the example,
$commonProtocol = getprotobyname("tcp");
Use the public protocol name to get a protocol type. The TCP public protocol is used here. If you want to use UDP or ICMP protocol, then you should change the parameters of the getprotobyname() function to "udp" or "icmp". Another alternative 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 generates a socket and returns an instance of the socket resource. After you have an instance of the 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 1337 port. Then you need to listen for all incoming socket connections.
socket_listen($socket);
After the fourth line, you need to understand all socket functions and their usage.
Table 4: Socket function
Function name Description
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 last error code
socket_close() Close a socket resource
socket_connect() Start a socket Connect
socket_create_listen() Open a socket listening on the specified port
socket_create_pair() Generate a pair of indistinguishable sockets into an array
socket_create() Generate a socket, which is equivalent to generating a socket data structure
socket_get_option() Get socket options
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 scattered/aggregated array
socket_iovec_alloc() This function creates a function that can send, receive, read and write iovec data structure
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() Get the current socket The last error code
socket_listen()  Listens to all connections from the specified socket
socket_read()  Reads the data of the specified length
socket_readv()  Reads the data from the scatter/aggregate array
socket_recv()  Ends the data from the socket to the cache
socket_recvfrom() Receive 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( ) Send a message to the socket
socket_sendto() Send 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 the socket option
socket_shutdown() This The function allows you to close the read, write, or specified socket
socket_strerror()  Return the detailed error with the specified error number
socket_write()  Write data to the socket cache
socket_writev()  Write data to the scatter/aggregate array
All the above functions are Regarding sockets in PHP, to use these functions, you must open your socket. If you do not open it, please edit your php.ini file and remove the comment in front of the following line:
extension=php_sockets.dll
If you cannot Remove the comments, then please use the following code to load the extension library:
if(!extension_loaded('sockets')) {
if(strtoupper(substr(PHP_OS, 3)) == "WIN") {
dl('php_sockets.dll');
}else{
dl('sockets.so');
}
}
?>
If you don't know if your socket is open, then you can use phpinfo() Function to determine whether the socket is open. You can check whether the socket is open by checking the phpinfo information.
View phpinfo()’s information about socket
◆ Generate a server
Now we will improve the first example. You need to listen to a specific socket and handle user connections.
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost', 1337);
socket_listen($socket);
// Accept any incoming connections to the server
$connection = socket_accept($socket);
if($connection){
socket_write($connection, "You have connected to the socket...nr");
}
?>
You should use your command prompt to run this example. The reason is because a server will be generated here, not a Web page. If you try to run this script using a web browser, there's a good chance it will exceed the 30-second limit. You can use the code below to set an infinite run time, but it is recommended to use the command prompt to run.
set_time_limit(0);
Simply test this script in your command prompt:
Php.exe example01_server.php
If you have not set the path to the php interpreter in your system's environment variables, then you will need to give php.exe specifies the detailed path. When you run the server, you can test the server by connecting to port 1337 via telnet.

There are three problems with the server side above: 1. It cannot accept multiple connections. 2. It only completes one command. 3. You cannot connect to this server through a web browser.
This first problem is easier to solve, you can use an application to connect to the server every time. But the next problem is that you need to use a Web page to connect to the server, which is more difficult. You can have your server accept the connection, write some data to the client (if it must write it), close the connection and wait for the next connection.
Improve on the previous code and generate the following code to make your new server:
// Set up our socket
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost', 1337); //socket_bind() Bind the socket to an IP address and port
socket_listen($socket);
// Initialize the buffer
$buffer = "NO DATA";
while(true) {
// Accept any connections coming in on this socket
$connection = socket_accept($socket);//socket_accept() Accept a Socket connection
printf( "Socket connectedrn");
// Check to see if there is anything in the buffer
if($buffer != ""){
printf("Something is in the buffer...sending data...rn") ;
socket_write($connection, $buffer . "rn"); //socket_write() Write data to the socket cache
printf("Wrote to socketrn");
}else {
printf("No Data in the bufferrn") ;
}
// Get the input
while($data = socket_read($connection, 1024, PHP_NORMAL_READ))//socket_read() Read data of specified length
{
$buffer = $data;
socket_write($connection , "Information Receivedrn");
printf("Buffer: " . $buffer . "rn");
}
socket_close($connection); //socket_close() Close a socket resource
printf("Closed the socketrnrn") ;
}
?>
What should this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection and once a connection is made it prints "Socket connected" on the screen on the server side. This server checks the buffer and if there is data in the buffer, it sends the data to the connected computer. Then it sends an acceptance message for this data. Once it accepts the message, it saves the message to the data, makes the connected computer aware of the message, and finally closes the connection. When the connection is closed, the server starts processing the next connection.
◆ It is easy to generate a client
to handle the second problem. You need to generate a php page, connect to a socket, send some data to its cache and process it. Then you have the processed data waiting, and you can send your data to the server. On another client connection, it will process that data.
The following example demonstrates the use of socket:
// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket,'localhost', 1337) ;
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)) {
if($buffer == “NO DATA”) {
echo(“

NO DATA

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

Buffer Data: “ . $buffer . “

”);
}
}
echo(“< ;p>Writing to Socket

”);
// Write some test data to our socket
if(!socket_write($socket, “SOME DATArn”)){
echo(“

Write failed< /p>”);
}
// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)){
echo(“

Data sent was: SOME DATA");
}
echo("

Done Reading from Socket

");
?>
This example code demonstrates The client connects to the server. The client reads the data. If this is the first connection to arrive in this cycle, the server will send "NO DATA" back to the client. If this happens, the client is on top of the connection. The client sends its data to the server, the data is sent to the server, and the client waits for a response. Once the response is received, it writes the response to the screen.


The above is the basic content of php Socket. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!