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

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 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 and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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 is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
