Home Backend Development PHP Tutorial Detailed explanation of socket communication in php

Detailed explanation of socket communication in php

Mar 16, 2018 am 11:34 AM
php socket communication

Sometimes our PHP program needs to communicate with other systems. For example, a company's official website provides product traceability information inquiry. The back-end website needs to communicate with the company's traceability system or ERP system. At this time, PHP network is required. For programming, PHP provides a sockets extension. The official website address is:

http://nl3.php.net/manual/zh/intro.sockets.php

This extension gives us the ability to directly manipulate sockets through php, so that we can communicate with other systems. We use sockets to work above the transport layer of the OSI network model, directly using TCP, UDP provides services, so you can use it as a client for other application layer protocols, such as simulating HTTP clients (browsers). Common smtp, pop, and ftp can be simulated with it. What is more interesting is that you can use it and allow TELNET's server interaction, these protocols are all application layer protocols, so they can all interact. Customized communication between systems requires custom protocols.

Here is an example to develop a simple file receiving server using PHP. Another PHP client program shows how to communicate with this server program. The code is as follows.

Server-side program:

<?php
/**
 * 本程序演示php网络编程:socket通讯 需要php开启php_sockets扩展
 * 这是一个简易的服务器程序,接收客户端发送的文件,保存后关闭
 * 通讯协议约定为:文件大小::文件扩展名::有效数据
 * 通讯结束标识符为:“-end-”
 * 在命令行或浏览器中执行均可,推荐命令行
 * 作者:云客【云游天下,作客四方】
 */

/****配置****/
//要绑定监听的本机ip地址和端口
$address = &#39;127.0.0.1&#39;;
$port = 81;

error_reporting(E_ALL);

//防止超时
set_time_limit(0);

//开启绝对刷送,禁止缓冲内容
ob_implicit_flush();

//创建套接字资源
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
//绑定套接字到端口
if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
//开始监听端口,参数5表示可以让5个连接请求在缓冲中排队
//排队的链接请求会在前一个连接断掉后才开始执行,该处缓冲排队数满五个后,后面的链接请求将直接忽略,客户端显示无法链接
//注意这个5并不是指可以并发进行5个链接,而是允许让5个后续链接进入排队
if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    //程序运行到此处进行阻塞,就像暂停执行一样,一旦有请求进入,该函数停止阻塞,返回链接资源
    if (($client_sock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    echo "[client connect start]\n";
    $data = ""; //接收的数据
    $data_size = -1; //接收的数据大小
    $received_size = 0; //实际接收的数据
    $ext_name = "txt"; //默认文件扩展名

    //开始与客户端交互
    do {
        //运行到该处产生阻塞,一旦有内容则停止阻塞状态,返回内容
        if (false === ($buf = socket_read($client_sock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client_sock)) . "\n";
            break 2; //读取不了就返回失败,此处的2会让客户端断掉链接后停止本模拟服务器
        }
        if ($data_size === -1) {//第一次接受数据,解析通讯协议
            $arr = explode("::", $buf, 3);
            $data_size = (int)$arr[0];
            $ext_name = $arr[1];
            $data .= $arr[2];
            $received_size += strlen($data);
            continue;
        }
        $data .= $buf;
        $received_size += strlen($buf);
        if ($data_size <= $received_size) {
            if ($data_size < $received_size) {
                $data = substr($data, 0, $data_size);
            }

            echo "received:" . $received_size . "/" . "total:" . $data_size;
            $talkback = "-end-"; //发送通讯结束标志
            socket_write($client_sock, $talkback, strlen($talkback));
            file_put_contents("servertest." . $ext_name, $data);
            break 2; //关闭服务器
        }

        echo $talkback = "received:" . $received_size . "\n";
        socket_write($client_sock, $talkback, strlen($talkback));


    } while (true);
    socket_close($client_sock);

} while (true);

socket_close($sock);
?>
Copy after login

Client-side program:

<?php
/**
 * 本程序演示php网络编程:socket通讯 需要php开启php_sockets扩展
 * 这是一个简易的客户端程序,向服务器发送文件
 * 通讯协议约定为:文件大小::文件扩展名::有效数据
 * 通讯结束标识符为:“-end-”
 * 在命令行或浏览器中执行均可,推荐命令行,需先开启服务器端
 * 作者:云客【云游天下,作客四方】
 */

/****配置****/
$file = "yunke.jpg"; //待发送的文件
//服务器ip和端口号
$address = &#39;127.0.0.1&#39;;
$port = 81;


error_reporting(E_ALL);

// 防止超时 
set_time_limit(0);

// 开启绝对刷送,不要缓冲输出
ob_implicit_flush(true);

//创建套接字资源
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit();
}
//打开到远程主机的链接
if (socket_connect($sock, $address, $port) === false) {
    echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    exit();
}

//构造一个很大的待发送数据 大约10MB
/*
$data = "";
for ($i = 1; $i <= 10000000; $i++) {
    $data .= "data:" . $i;
}
$data = $data . $data . $data;
*/

$data = file_get_contents($file);
$data_size = strlen($data);
$arr_temp = explode(&#39;.&#39;, $file);
$ext_name = end($arr_temp);
$sock_data = $data_size . "::" . $ext_name . "::" . $data;

//发送数据给远程主机
while (true) {
    $sock_data_size = strlen($sock_data);
    $send_size = socket_write($sock, $sock_data, $sock_data_size);
    if ($send_size === false) {
        echo "send false:" . socket_strerror(socket_last_error($sock)) . "\n";
        socket_close($sock);
        echo "[client shutdown]\n";
        exit();
    }
    if ($send_size == $sock_data_size) {
        break;
    }
    $sock_data = substr($sock_data, $send_size);
}

//读返回数据
while (true) {
    if (false === ($out = socket_read($sock, 2048))) {
        echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break 1;
    }

    echo "server: " . $out . "\n";
    if (substr($out, -5) == "-end-") { //约定结束标志
        break;
    }
}
//关闭套接字资源
socket_close($sock);
echo "[client shutdown]\nsend data:" . format($data_size);

function format($byte = 0)
{
    if ($byte > 1024 * 1024) {
        return ceil($byte / (1024 * 1024)) . "MB";
    } elseif ($byte > 1024) {
        return ceil($byte / 1024) . "KB";
    } else {
        return $byte . " Byte";
    }
}
Copy after login


This example shows transmitting a file to the server through a TCP short link. In an actual project, the communication module will not be so simple, and more issues need to be considered

For example:

Whether a long connection method is required (data is transmitted back and forth multiple times in a tcp link), data verification to prevent damage, and the size between different systems Endianness issues, custom communication protocols, packet sticking issues, timeout processing, concurrent access, flow control, TCP packet unpacking, etc.

If you want to learn more about PHP network programming and above All the above mentioned require systematic learning. It is recommended to take a look at the implementation of Workerman

It is a socket server framework written in PHP to help solve socket communication problems. You can use it to build an automatic Define the server, etc.
workermanThe official website address is: http://www.workerman.net/

The following two more viewing servers are provided Sample program for HTTP headers and browser headers:

The following example views the header information returned by the server, modifies the server address that needs to be viewed, and then accesses the script in the browser. Can:

<?php
error_reporting(E_ALL);

// 防止超时 
set_time_limit(0);

// 开启绝对刷送,不要缓冲输出
ob_implicit_flush(true);

$address = &#39;www.qq.com&#39;; //要查看的服务器
$port=80;

//创建套接字资源
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit();
}
//打开到远程主机的链接
if (socket_connect($sock, gethostbyname($address), $port) === false) {
    echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    exit();
}

//构造http头
$msg = "GET / HTTP/1.1 \r\n";
$msg .= "Host: {$address}\r\n";
$msg .= "Connection: Close\r\n\r\n";  
//指示服务器发回完毕就断开,不必等等其他资源的链接
//如果没有该行会,服务器会一直等待我方继续发送数据,直到超时关闭
//而我方不会再发送,这个会让下面的socket_read函数互为等待,等很久

//发送给远程主机
socket_write($sock, $msg, strlen($msg));

$str="";
while ($out = @socket_read($sock, 2048*4)) {
    $str.=$out;
}
$str=explode("\r\n\r\n", $str);
$str=$str[0];
if($str)
{
    echo "<pre class="brush:php;toolbar:false">\r\n".$str."\r\n
"; }else{ echo "nothing"; } //关闭套接字资源 socket_close($sock);
Copy after login

The following is an example of viewing the browser header, you can easily view the session information sent by the browser
First Make sure port 80 is closed, then modify the host file of the machine, direct the URL you want to access to the 127.0.0.1 address of the machine, use the php command line mode to start this script, and then use the browser to access the URL that has been directed. The program will always be open. If you need to close it, please use the ctrl+c key combination in the console. The program is as follows:

<?php
error_reporting(E_ALL);

//防止超时
set_time_limit(0);

//开启绝对刷送,禁止缓冲内容
ob_implicit_flush();

$address = &#39;127.0.0.1&#39;;
$port = 80;

//创建套接字资源
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
//绑定套接字到端口
if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
//开始监听端口,参数5表示可以让5个连接请求在缓冲中排队
//排队的链接请求会在前一个连接断掉后才开始执行,该处缓冲排队数满五个后,后面的链接请求将显示无法链接
//注意这个5并不是指可以并发进行5个链接,而是允许让5个后续链接进入排队
if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    //程序运行到此处进行阻塞,就像暂停执行一样,一旦有请求进入,该函数停止阻塞,返回链接资源
    //可以使用socket_set_nonblock函数设置非阻塞模式
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    
    //链接成功后在控制台显示提示
    echo "[client start ".date("Y-m-d H:i:s")."]\n\n";
    
    do {
        //运行到该处产生阻塞,一旦有内容则停止阻塞状态,返回内容
        if (false === ($buf = socket_read($msgsock, 2048*6))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2; //读取不了就返回失败,此处的2会让客户端断掉链接后停止本模拟服务器
        }
        $talkback ="HTTP/1.1 200 OK\r\n\r\n";
        $talkback .= date("Y-m-d H:i:s")."\nBrowser HTTP Headers:\n\n".$buf."\n";
        //向客户端显示该内容
        socket_write($msgsock, $talkback, strlen($talkback));
        //向服务器控制台显示该内容
        echo "$buf\n";
        break ; //中断本次与浏览器的链接
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>
Copy after login

Related recommendations:

How to implement socket communication to obtain the local source port number in Linux

PHP Socket server construction and testing example sharing

Simple method to use Socket in PHP

The above is the detailed content of Detailed explanation of socket communication 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

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)

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

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

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

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