How to implement long connection in php socket
What is a long connection?
Friends should have seen many online chat tools and web online chat tools. There is a familiar function in the school. If someone replies to you, a prompt will appear immediately on the website. You have not refreshed the page at this time. Gmail also has this function. If a new email is received in the mailbox, the website will remind you immediately, even if you The web page has never been refreshed. Speaking of which, everyone must be familiar with this, which is to reuse a link for continuous data interaction. Nowadays, many Internet business scenarios require the support of long connections, such as games, chats, information push, etc. So many similar functions are inseparable from long connections. The previous chapter introduced php socket communication, this chapter will introduce the php socket long connection.
Long connections and short links
Short connections generally request data from a single item. The server cannot actively "push" the data to the client, but with a long connection Much better, using the combination of back-end and front-end technologies, the server's "push information" function can be realized. If there is an update in the database, the back-end program can "push out" the data immediately, instead of repeatedly requesting it multiple times. The connection is established and disconnected multiple times.
There are probably several explanations as follows:
The so-called long connection refers to maintaining the connection regardless of whether it is used or not after establishing a SOCKET connection, but the security is poor; the so-called short connection Connection refers to establishing a SOCKET connection and disconnecting immediately after sending and receiving data. Generally, banks use short connections
Long connections refer to maintaining connections in TCP-based communications. Regardless of whether data is currently being sent or received. The short connection means that the connection is only made when there is data transmission, and the connection is closed after the client-server communication/transmission of data is completed.
Communication method
There are two connection methods between each network element: long connection and short connection. The so-called long connection means that multiple data packets can be sent continuously on a TCP connection. During the period when the TCP connection is maintained, if no data packets are sent, both parties need to send detection packets to maintain the connection. A short connection means that when the communicating parties have data exchange, a TCP connection is established. After the data is sent, the TCP connection is disconnected. That is, each TCP connection only completes the sending of a pair of CMPP messages.
At this stage, it is required that ISMGs must use long-term connection communication methods. It is recommended that long-term connection communication methods be used between SPs and ISMGs.Short connection: For example, http, it only connects, requests, and closes. The process time is short. If the server does not receive the request within a period of time, it can close the connection. Long connection: Some services need to connect to the server for a long time, such as CMPP, and generally need to be maintained online by themselves.
Realizing socket long connection
Every time we access a PHP script, we will wait until all PHP scripts are executed. Get the return result. If we need a script to run continuously, then we must use PHP long connection to achieve the purpose of operation.
If you want to play with long connections, you need to deal with sockets. Socket encapsulation is naturally indispensable. Below is the code to perform a long socket connection.
The example code is as follows:
<?php $sfd = socket_create(AF_INET, SOCK_STREAM, 0); socket_bind($sfd, "0.0.0.0", 1234); socket_listen($sfd, 511); socket_set_option($sfd, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_nonblock($sfd); $rfds = array($sfd); $wfds = array(); do{ $rs = $rfds; $ws = $wfds; $es = array(); $ret = socket_select($rs, $ws, $es, 3); //读取事件 foreach($rs as $fd){ if($fd == $sfd){ $cfd = socket_accept($sfd); socket_set_nonblock($cfd); $rfds[] = $cfd; echo "new client coming, fd=$cfd\n"; }else{ $msg = socket_read($fd, 1024); if($msg <= 0){ //close }else{ echo "on message, fd=$fd data=$msg\n"; } } } //写入事件 foreach($ws as $fd){ socket_write($fd, ........); } }while(true); ?>
Let’s improve the efficiency:
<?php $sfd = stream_socket_server ('tcp://0.0.0.0:1234', $errno, $errstr); stream_set_blocking($sfd, 0); $base = event_base_new(); $event = event_new(); event_set($event, $sfd, EV_READ | EV_PERSIST, 'ev_accept', $base); event_base_set($event, $base); event_add($event); event_base_loop($base); function ev_accept($socket, $flag, $base) { $connection = stream_socket_accept($socket); stream_set_blocking($connection, 0); $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $connection); event_buffer_base_set($buffer, $base); event_buffer_timeout_set($buffer, 30, 30); event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff); event_buffer_priority_set($buffer, 10); event_buffer_enable($buffer, EV_READ | EV_PERSIST); } function ev_error($buffer, $error, $connection) { event_buffer_disable($buffer, EV_READ | EV_WRITE); event_buffer_free($buffer); fclose($connection); } function ev_read($buffer, $connection) { $read = event_buffer_read($buffer, 256); //do something.... } ?>
Follow As the number of people increases and concurrency increases, a single process can no longer meet the demand. There are ready-made extensions and libraries to solve this problem, such as: swoole, workerman, etc.? However, when we use PHP to develop the web, we do not use webserver-related libraries for development, right? We just do a simple echo. These complicated things are all handed over to nginx or apache, and they take the lead without hesitation, so that we can concentrate on writing logic. Writing socket services is no more advanced than writing web services. They are all coding and completing requirements. The communication layer is fixed, but one is completed by nginx and the other is completed by yourself. . But now you don’t need to complete it yourself. A solution similar to nginx+fpm, fooking+fpm=php long connection, gateway is used to carry the connection, and router is used to forward messages.
The code is as follows:
<?php $sid = $_SERVER['SESSIONID'];//这是sessionid $data = file_get_contents("php://input");//这样就能拿到请求内容了 //想要返回消息只需要两步 header('Content-Length: 11');//返回给客户端字节数 echo "hello world"; //想要给别的用户发消息 include 'api.php'; $router = new RouterClient('router host', 'router port'); $router->sendMsg(用户sessionid, "fuck you"); //想要给所有人要消息 $router->sendAllMsg("fuck all"); //想给指定组发消息(类似redis的pub/sub) $router->publish("channel name", "fuck all"); ?>
[Related tutorial recommendations]
1. "php.cn Dugu Jiujian (4 )-php video tutorial》
2. A complete set of tutorials on PHP programming from entry to master
The above is the detailed content of How to implement long connection in php socket. 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

AI Hentai Generator
Generate AI Hentai for free.

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

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

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

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

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

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.
