Home Backend Development PHP Tutorial Detailed explanation of the main socket function syntax and usage examples in php

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

May 22, 2017 pm 02:49 PM

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 in php? 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 between blocking mode and non-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. 服务器端

<?php
//确保在连接客户端时不会超时
set_time_limit(0);
$ip = &#39;127.0.0.1&#39;;
$port = 1935;
/*
 +-------------------------------
 *    @socket通信整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_bind
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 */
/*----------------    以下操作都是手册上的    -------------------*/
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
    echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n";
}
if(($ret = socket_bind($sock,$ip,$port)) < 0) {
    echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";
}
if(($ret = socket_listen($sock,4)) < 0) {
    echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";
}
$count = 0;
do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
        break;
    } else {
        
        //发到客户端
        $msg ="测试成功!\n";
        socket_write($msgsock, $msg, strlen($msg));
        
        echo "测试成功了啊\n";
        $buf = socket_read($msgsock,8192);
        
        
        $talkback = "收到的信息:$buf\n";
        echo $talkback;
        
        if(++$count >= 5){
            break;
        };
        
    
    }
    //echo $buf;
    socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Copy after login

2. 客户端

<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\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 "试图连接 &#39;$ip&#39; 端口 &#39;$port&#39;...\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 = &#39;&#39;;
if(!socket_write($socket, $in, strlen($in))) {
    echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
}else {
    echo "发送到服务器信息成功!\n";
    echo "发送的内容为:<font color=&#39;red&#39;>$in</font> <br>";
}
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles