Table of Contents
Socket Introduction" >Socket Introduction
Socket function introduction" >Socket function introduction
socket_create
socket_bind
socket_listen
socket_accept
socket_write
socket_read
Home Backend Development PHP Tutorial Commonly used functions in php socket programming and the implementation of simple c/s interaction

Commonly used functions in php socket programming and the implementation of simple c/s interaction

Jul 26, 2018 am 10:18 AM
php socket programming network programming

The content of this article is about commonly used functions in php socket programming and the implementation of simple c/s interaction. The content is very detailed. Friends in need can refer to it. I hope it can help you.

Socket Introduction

Official explanation of Socket:
The most commonly used solution in network programming is the Client/Server (client/server) model. In this scenario the client application requests services from the server program. A service program usually listens for requests for the service at a well-known address. That is to say, the service process remains dormant until a client makes a connection request to the service's address. At this moment, the service program is "awakened" and provides services to the client - reacting appropriately to the client's request. In order to facilitate network programming of this Client/Server model, in the early 1990s, Microsoft and several other companies jointly developed a set of network programming interfaces under WINDOWS, namely the Windows Sockets specification. It is not a network protocol, but a network programming interface. A set of open network programming interfaces under Windows that support multiple protocols. Now Winsock has basically become protocol-independent. You can use Winsock to call functions of multiple protocols, but the TCP/IP protocol is more commonly used. Socket actually provides a communication port in the computer through which it can communicate with any computer that has a Socket interface. The application transmits on the network, and the information received is realized through this Socket interface

We can simply understand Socket as a pipe that can connect different computer applications on the network, and transfer a bunch of data from If the A end of the pipe is thrown in, it will come out from the B end of the pipe (it can also come out from the C, D, E, F... ends).

Note: We will use different words to modify socket in different contexts. You only need to have a concept of it, because socket itself has no real meaning. Entity

Socket function introduction

Socket communication will proceed through several stages: Socket creation, Socket binding, Socket monitoring, Socket sending and receiving, and Socket closing. We list them below. Several common functions that are most commonly used and essential in PHP network programming are further explained.

socket_create

TODO: Create a new socket resource
Function prototype: resource socket_create (int $domain, int $type, int $protocol)
It contains three parameters, as follows:

  • domain: AF_INET, AF_INET6, AF_UNIX, the definition of AF is address family, address Family means, we commonly use ipv4, ipv6

  • type: SOCK_STREAM, SOCK_DGRAM, etc. The most commonly used one is SOCK_STREAM, a SOCKET type based on byte stream, It is also the type used by TCP protocol

  • protocol: SOL_TCP, SOL_UDP This is the specific transmission protocol used. Generally, we choose TCP for reliable transmission, and we generally choose UDP protocol for game data transmission

socket_bind

TODO: Bind the created socket resource to a specific ip address and port
Function prototype: bool socket_bind (resource $socket, string $ address [, int $port = 0 ] )

It contains three parameters, as follows:

  • socket: Use socket_create The created socket resource can be considered as the id corresponding to the socket

  • address: ip address

  • port: listening port number, WEB server default Port 80

socket_listen

TODO: Monitor the sending and receiving operations of socket resources at a specific address
Function prototype: bool socket_listen (resource $socket [ , int $backlog = 0 ] )

It contains two parameters, as follows:

  • socket: Created using socket_create Socket resource

  • backlog: The maximum length of the connection queue waiting to be processed

socket_accept

TODO: After listening, receive a The upcoming new connection, if the connection is successfully established, will return a new socket handle (you can understand it as a child process, usually the parent process is used to receive new connections, and the child process is responsible for specific communication)
Function prototype: resource socket_accept ( resource $socket )

  • socket: socket resource created using socket_create

socket_write

TODO: Send the specified data to the corresponding socket pipe
Function prototype: int socket_write (resource $socket, string $buffer [, int $length])

  • socket: socket resource created using socket_create

  • buffer: written to socket resource Data in

  • length: Controls the length of buffer written to the socket resource, if the length is greater than buffer’s capacity, take the capacity of buffer

socket_read

TODO: Get the transmitted data
Function prototype: int socket_read (resource $socket, int $length)

  • socket: The socket resource created using socket_create

  • length: buffer# in the socket resource ##The length

socket_close

TODO: Close the socket resource

Function prototype:
void socket_close (resource $socket)

  • socket: The resources generated by

    socket_accept or socket_create cannot be used to close stream resources

stream_socket_server

Since the process of creating a SOCKET is always socket, bind, and listen, PHP provides a very convenient function to create, bind ports, and listen to ports at once

Function prototype:

resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )

  • local_socket: protocol name://address:port number

  • errno: error code

  • errstr: Error message

  • #flags: Only use part of the function

  • context: Resource stream created using the

    stream_context_create function Context

socket implements C/S interaction

Based on the above functions, we can easily build a socket communication program (here I hope Readers can create a separate directory such as

socket (because we will create many files later). We first edit a server program server.php, as follows:

<?php date_default_timezone_set("Asia/Shanghai");
error_reporting(E_NOTICE );

/*  确保在连接客户端时不会超时   */
set_time_limit(0);

$ip = &#39;127.0.0.1&#39;;
$port = 8090;

/*
 +-------------------------------
 *    @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() Why failure is:".socket_strerror($sock)."\n";
}

if(($ret = socket_bind($sock,$ip,$port)) < 0) {
    echo "socket_bind() Why failure is:".socket_strerror($ret)."\n";
}

if(($ret = socket_listen($sock,4)) < 0) {
    echo "socket_listen() Why failure is:".socket_strerror($ret)."\n";
}

echo "Start time:".date(&#39;Y-m-d H:i:s&#39;) . PHP_EOL;
echo "Listening at ".$ip.&#39;:&#39;.$port.PHP_EOL;


do {
    /*  创建新的连接  */
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
        break;
    } else {
        
    # 连接成功输出 Socket id
    $i = (int)$msgsock;
    echo "welcome client $i";

        # 向客户端通信(反馈)
        $msg ="连接成功!\n";
        socket_write($msgsock, $msg, strlen($msg));
    }
    socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Copy after login
Then Edit a client program

client.php as follows:

<?php set_time_limit(0);
$port = 8090;
$ip = "127.0.0.1";

/*
 +-------------------------------
 *    客户端 socket 连接整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 */


/**
 * @socket_connect:客户端发起套接字连接
 * @param socket  resource $socket       创建的$socket资源
 * @param address string   SOCK_STREAM   IP地址|Unix套接字
 * @param port    int                    端口
 */

/**
 * @socket_create:创建并返回一个套接字
 * @param domain   string AF_INET         IPV4 网络协议
 * @param type     string SOCK_STREAM     全双工字节流(可用的套接字类型)
 * @param protocol string SOL_TCP         具体协议(IPV4下的TCP协议)
 * @param return   套接字
 */

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}else {
    echo "try to connect &#39;$ip&#39; port: &#39;$port&#39;...\n";
}


$result = socket_connect($socket, $ip, $port);  #socket_connect的返回值应该是boolean值
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
    # 连接成功输出提示信息
    echo "connect successfully\n";

    # 向服务端发送数据
    socket_write($socket, " hello ", 1024);

    # 获取服务端数据
    $result = socket_read($socket, 1024);
    echo "服务器回传数据为:" . $result;


    echo "CLOSE SOCKET...\n";
    socket_close($socket);
    echo "CLOSE OK\n";    
    
}



?>
Copy after login
Then we open the terminal (command line) and enter the file directory to execute in sequence:

php server.php
php client.php
Copy after login
The running effect is as follows:

Commonly used functions in php socket programming and the implementation of simple c/s interaction

NoteWhen the server is listening, the process is suspended and no other operations can be performed. You may need to start another terminal to execute the client Terminal program

Related recommendations:

How does PHP and MySql realize background data reading? (Code)

thinkphp5 uses the workerman timer to crawl regularly Get the code of the site content

The above is the detailed content of Commonly used functions in php socket programming and the implementation of simple c/s interaction. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
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,

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.

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

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles