Detailed explanation of the main socket function syntax and usage examples in php

伊谢尔伦
Release: 2023-03-07 20:26:01
Original
4126 people have browsed it

In actual development, if you want to create a socket-based application, you need to understand the socket operation methods in detail. If you want to understand and use these operation methods proficiently, you need to first understand the various socket functions in PHP. In the previous chapter, we introduced in detail what is the socket inphp? Here is an introduction to the socket function in php. There are dozens of socket functions in PHP. Here are some main socket functions to introduce.

Their syntax format parameters are as follows:

1.socket_create

socket_create ( int $domain , int $type , int $protocol )
Copy after login

This function is used to create a socket, it has three parameters, and the return value is a handle (resource).

$domain specifies the communication protocol family used when creating the socket. The optional values are:

AF_INET: Internet protocol based on IPv4

AF_INET6: Based on Internet Protocol for IPv6

AF_UNIX: UNIX local communication protocol

$type specifies the interaction type of socket communication, its optional values are:

SOCK_STREAM: Provided Serialized, reliable, full-duplex, connection-based byte stream transmission, supports TCP

SOCK_DGRAM: provides datagram style, connectionless, fixed maximum length, automatic addressing function Transmission, supports UDP

SOCK_SEQPACKET: Provides serialized, reliable, dual-channel, connection-based datagram transmission

SOCK_RAW: Provides the original network access protocol, special protocols can be built manually Type of socket, supports ICMP requests (such as ping)

SOCK_RDM: Provides reliable datagram transmission, the order cannot be guaranteed

$protocol specifies which specific transmission protocol the socket uses, including ICMP, UDP, TCP, the constant SOL_UDP corresponds to UDP, and the constant SOL_TCP corresponds to the constant TCP.

2.socket_bind

socket_bind ( resource $socket , string $address [, int $port = 0 ] )
Copy after login

This function is used to bind the IP address and port to the handle created by socket_create. It has three parameters and returns a Boolean value.

$socket is a required parameter, representing the handle created by the socket_create function

$address is a required parameter, representing the IP address to be bound

$port is an optional parameter, representing the port number to be bound and specifying which port is used to listen for socket connections. When the first parameter of the socket_create function is AF_INET, this parameter needs to be specified.

3.socket_listen

socket_listen ( resource $socket [, int $backlog = 0 ] )
Copy after login

This function is used to listen to the socket connection that is about to be connected. It can only be used when the interaction type of the socket is SOCK_STREAM or SOCK_SEQPACKET

Used, it has two parameters and returns a Boolean value.

$socket is a required parameter, representing the handle created by the socket_create function (and has been bound to the host)

$backlog is an optional parameter, representing the queue waiting to be processed (backlog is allowed ) maximum number of connections.

4.socket_set_block

socket_set_block ( resource $socket )
Copy after login

This function is used to set the socket handle to blocking mode. It has only one required parameter and returns a Boolean value. It can convert a non-blocking mode socket into blocking mode.

When performing an operation (receive, send, connect, accept, etc.) in a blocking mode socket, the script will pause execution until it receives a signal or it completes the operation.

$socket is a required parameter, representing a valid socket handle (created by socket_create or socket_accept).

Explain the difference betweenblocking modeandnon-blocking mode:

non-blocking means that the function operation will not wait until the result cannot be obtained immediately. Blocks the current thread and returns immediately. Blocking means that you are not allowed to come back until you are done. You must get a response from the other party before you can continue with the next step. Especially when there are many users, it is necessary to set it to non-blocking. If it is blocking mode, if two clients are connected at the same time, when the server is processing one client's request, the other client's request will be blocked. Only after the previous client's affairs are processed, the latter client's request will be processed. will be responded to.

5.socket_write

socket_write ( resource $socket , string $buffer [, int $length = 0 ] )
Copy after login

This function is used to write buffer data of a specified size to the socket. It has three parameters and returns the number of bytes of the written data. .

$socket is a required parameter and represents a valid socket handle.

$buffer is a required parameter, specifying the string data to be written.

$length is an optional parameter that specifies the number of bytes of data to be written to the socket in turn. If its value is greater than the number of bytes in $buffer, it will silently intercept it to $buffer. Length in bytes.

6.socket_read

socket_read ( resource $socket , int $length [, int $type = PHP_BINARY_READ ] )
Copy after login

This function is used to read data of specified byte length from the socket. It has three parameters and returns the read string data.

$socket is a required parameter and represents a valid socket handle.
$length is a required parameter, specifying the length of bytes to be read.

$type is an optional parameter. The default value is PHP_BINARY_READ, which means safe reading of binary data; the other optional value is PHP_NORMAL_READ, which means to stop reading when \r or \n is encountered.

7.pfsockopen

pfsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )
Copy after login

该函数用于实现一个持久的socket连接,即长连接,返回一个句柄。它与 fsockopen 的区别在于,pfsockopen 建立的连接,在脚本执行完毕后,并不会断开。

8.socket_set_option

socket_set_option ( resource$socket , int$level , int$optname , mixed$optval )
Copy after login

该函数用于设置socket的控制选项,有四个参数,返回布尔值。

$socket 是必选参数,代表一个有效的socket句柄。

$level 是必选参数,指定option起作用的协议级别,一般取常量 SOL_SOCKET。

$optname 是必选参数,指定要控制的选项名称。

$optval 是必选参数,指定选项的值。

9.socket_last_error

socket_last_error ([ resource$socket ] )
Copy after login

该函数用于获取任何socket函数产生的最后错误代号,返回值为整型。

10.socket_strerror

socket_strerror ( int $errno )
Copy after login

该函数用于获取错误代号代表的错误描述,返回值为字符串。

以上所有的函数都是PHP中关于socket的,使用这些函数,你必须把你的socket打开,如果你没有打开,请编辑你的php.ini文件,去掉下面这行前面的注释:

extension=php_sockets.dll
Copy after login

如果你不知道你的socket是否打开,那么你可以使用phpinfo()函数来确定socket是否打开。

下面通过创建一个服务端和客户端的例子来说明这些函数的用法:

  1. 服务器端

= 5){ break; }; } //echo $buf; socket_close($msgsock); } while (true); socket_close($sock); ?>
Copy after login

2. 客户端

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 < 0) { 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 < 0) { echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n"; }else { echo "连接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 "发送到服务器信息成功!\n"; echo "发送的内容为:$in 
"; } while($out = socket_read($socket, 8192)) { echo "接收服务器回传信息成功!\n"; echo "接受的内容为:",$out; } echo "关闭SOCKET...\n"; socket_close($socket); echo "关闭OK\n"; ?>
Copy after login

【相关教程推荐】

1. 《php.cn独孤九贱(4)-php视频教程

2.php编程从入门到精通全套教程

The above is the detailed content of Detailed explanation of the main socket function syntax and usage examples in php. For more information, please follow other related articles on the PHP Chinese website!

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
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!