


Implementing PHP and websocket chat room based on Swoole_php example
websocket
Websocket is just a network communication protocol
Just like http, ftp, etc. are all network communication protocols; don’t think too much;
Compared to non-persistent protocols like HTTP, Websocket is a protocol for persistent network communication;
The relationship between WebSocket and HTTP
There is intersection, but not all.
Websocket just borrows part of the HTTP protocol to complete a handshake. (HTTP’s three-way handshake is only completed once here)
Comparison of http and websocket request headers:
HTTP:
Originally, the client requested the server with a letter through http (horseback riding), the server processed the request (wrote a reply), and returned again through http (horseback riding); the link was broken;
WebSocket:
The client requests the server with a letter through http (horseback), but at the same time, it carries Upgrade: websocket
and Connection: Upgrade
(two pipes). If the server supports the WebSocket protocol (an interface with two pipes) , using the Websocket protocol to return available information (discarding the horse). Afterwards, the transmission of information will use these two pipes, unless one party artificially cuts off the pipe; if the server does not support it, the client fails to request the link and returns an error message;
Comparison of http and websocket response headers:
The difference between websocket, ajax polling and long poll
The first is ajax polling. The principle of ajax polling is very simple. It allows the browser to send a request every few seconds to ask the server if there is new information
Scene reproduction:
Client: La la la, is there any new information (Request)
Server: No (Response)
Client: La la la, is there any new information (Request)
Server: None. . (Response)
Client: La la la, is there any new information (Request)
Server: You are so annoyed, no. . (Response)
Client: La la la, is there any new message (Request)
Server: Okay, okay, here it is for you. (Response)
Client: La la la, is there any new message (Request)
Server:. . . without. . . . without. . No
long poll In fact, the principle is similar to ajaxpolling. They both use polling and will not be discussed here;
As can be seen from the above, polling is actually continuously establishing HTTP connections and then waiting for the server to process, which can reflect another characteristic of the HTTP protocol, passivity. At the same time, after each http request and response, the server discards all client information. The next request must carry identity information (cookie), stateless;
The emergence of Websocket has neatly solved these problems;
So the above scenario can be modified as follows.
Client: La la la, I want to establish the Websocket protocol, the required service: chat, Websocket protocol version: 17 (HTTP Request)
Server: ok, confirmed, has been upgraded to Websocket protocol (HTTP Protocols Switched)
Client: Please push it to me when you have information. .
Server: ok, I will tell you sometimes.
Client: balab starts fighting with alabala
Server: Sora Aoi
Client: I have a nosebleed, let me wipe it...
Server: Hahabul Education is awesome hahahaha
Server: I’m laughing so hard haha
Swoole
However, in order to use PHP and HTML5 to complete a WebSocket request and response, I traveled thousands of miles and found Swoole deep in the jungle:
PHP language’s asynchronous, parallel, high-performance network communication framework, written in pure C language, provides PHP language’s asynchronous multi-threaded server, asynchronous TCP/UDP network client, asynchronous MySQL, database connection pool, AsyncTask, message queue, Millisecond timer, asynchronous file reading and writing, asynchronous DNS query.
Supported services:
HttpServer
WebSocket Server
TCP Server
TCP Client
Async-IO(asynchronous)
Task(scheduled task)
Environment dependencies:
Only supports Linux, FreeBSD, MacOS, type 3 operating systems
Linux kernel version 2.3.32 or above
PHP5.3.10 or above
gcc4.4 or above version or clang
cmake2.4+, you need to use cmake when compiling to libswoole.so as a C/C++ library
Installation:
You must ensure that the following software is present in the system:
php-5.3.10 or higher
gcc-4.4 or higher
make
autoconf
Swoole runs as a PHP extension
Installation (root permission):
cd swoole
phpize
./configure
make
sudo make install
Configure php.ini
extension=swoole.so
For those who want to study Swoole, read the manual yourself (although it is not well written, you can still understand it)
Make a chat room
Server side: socket.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
Client: Socket.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
The above is the entire content of implementing PHP and websocket chat rooms based on Swoole. I believe this article will be helpful for everyone to learn PHP and websocket and develop chat rooms.

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

Alipay PHP...

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

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,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
