How to implement simple php socket communication
socket, also commonly known as "socket", is used to describe the IP address and port, and is the handle of a communication chain. Applications usually make requests to the network or respond to network requests through "sockets". Socket is neither a program nor a protocol. It is just a set of abstract APIs for the communication layer provided by the operating system. The previous chapter introduced some common and important functions of php socket, which will be used in socket communication.
Communication requires server and client components:
Server side: Use php to initialize the socket and then bind a port to monitor the port . Call accept to block and wait for the client to connect.
Client: The client initializes a socket and then connects to the server. If the connection is successful, the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection, and the interaction ends.
Client-server are applications that can interact with each other. The interaction between client and server requires a connection. Socket programming is responsible for establishing interactive connections between applications.
Socket connection process
Depending on how the connection is initiated and the target to which the local socket is connected, the connection process between sockets can be divided into three steps. : Server monitoring, client request, connection confirmation.
(1) Server monitoring: The server-side socket does not locate the specific client socket, but is in a state of waiting for connection and monitors the network status in real time.
(2) Client request: refers to a connection request made by the client's socket, and the target to be connected is the server's socket. To do this, the client's socket must first describe the server's socket to which it wants to connect, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
(3) Connection confirmation: means that when the server-side socket listens or receives the connection request of the client socket, it responds to the request of the client socket and establishes a new Thread, sends the description of the server-side socket to the client. Once the client confirms this description, the connection is established. The server-side socket continues to be in the listening state and continues to receive connection requests from other client sockets.
Socket principle can refer to the flow chart below:
The following is a simple implementation of socket communication through a server-client code example. The whole process
1. Its server code:
<?php set_time_limit(0); //限制执行时间 0为不限制 $ip = '127.0.0.1'; $port = 8001;//端口 /** socket通信整个过程 socket_create //创建一个套接字 socket_bind //给套接字绑定 ip 和端口 socket_listen //监听套接字上的连接 socket_accept //接受一个socket连接 socket_read //接收客户端 发送的数据 socket_write //将数据写到 socket 缓存 向客户端发送 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); ?>
Run the php file, After running, the result should not be visible, you can use netstat -ntlp Check whether port 8001 is occupied. See picture below.
2. Its client code:
<?php error_reporting(E_ALL); set_time_limit(0); echo "socket通信客户端\n"; $port = 8001;//端口 $ip = "127.0.0.1";//ip /** socket连接整个过程 socket_create //建立一个socket 连接 socket_connect // 开始一个socket连接 连接服务端 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\nfirst blood\r\n"; $out = ''; if(!socket_write($socket, $in, strlen($in))) { echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n"; }else { echo "发送到服务器信息成功!\n"; echo "发送的内容为:<font color='red'>$in</font> <br>"; } while($out = socket_read($socket, 8192)) { echo "接收服务器回传信息成功!\n"; echo "接受的内容为:",$out; } echo "关闭SOCKET...\n"; socket_close($socket); echo "关闭OK\n"; ?>
Look at the server window result:
Note: The characteristics of the PHP language determine that in this regard, php is only suitable for the client, not the server.
【Recommended related tutorials】
1. "php.cn Dugu Jiujian (4)-php video tutorial"
2. #php programming from entry to master a complete set of tutorials
The above is the detailed content of How to implement simple php socket communication. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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,

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

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

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