search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the main socket function syntax and usage examples in php

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 )

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 ] )

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 ] )

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 )

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 ] )

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 ] )

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") ]]]] )

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

8. socket_set_option

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

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

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

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

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

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

9. socket_last_error 

socket_last_error ([ resource$socket ] )

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

10. socket_strerror 

socket_strerror ( int $errno )

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

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

extension=php_sockets.dll

如果你不知道你的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);
?>

2. 客户端

<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2 id="TCP-IP-nbsp-Connection">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";
?>

【相关教程推荐】

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software