search
HomeBackend DevelopmentPHP TutorialImplementing 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

//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
  $fd[] = $request->fd;
  $GLOBALS['fd'][] = $fd;
  //$ws->push($request->fd, "hello, welcome\n");
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
  $msg = 'from'.$frame->fd.":{$frame->data}\n";
//var_dump($GLOBALS['fd']);
//exit;
  foreach($GLOBALS['fd'] as $aa){
    foreach($aa as $i){
      $ws->push($i,$msg);
    }
  }
  // $ws->push($frame->fd, "server: {$frame->data}");
  // $ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
  echo "client-{$fd} is closed\n";
});

$ws->start();

Client: Socket.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="发送数据" onclick="song()">
</body>
<script>
  var msg = document.getElementById("msg");
  var wsServer = 'ws://192.168.1.253:9502';
  //调用websocket对象建立连接:
  //参数:ws/wss(加密)://ip:port (字符串)
  var websocket = new WebSocket(wsServer);
  //onopen监听连接打开
  websocket.onopen = function (evt) {
    //websocket.readyState 属性:
    /*
    CONNECTING  0  The connection is not yet open.
    OPEN  1  The connection is open and ready to communicate.
    CLOSING  2  The connection is in the process of closing.
    CLOSED  3  The connection is closed or couldn't be opened.
    */
    msg.innerHTML = websocket.readyState;
  };

  function song(){
    var text = document.getElementById('text').value;
    document.getElementById('text').value = '';
    //向服务器发送数据
    websocket.send(text);
  }
   //监听连接关闭
//  websocket.onclose = function (evt) {
//    console.log("Disconnected");
//  };

  //onmessage 监听服务器数据推送
  websocket.onmessage = function (evt) {
    msg.innerHTML += evt.data +'<br>';
//    console.log('Retrieved data from server: ' + evt.data);
  };
//监听连接错误信息
//  websocket.onerror = function (evt, e) {
//    console.log('Error occured: ' + evt.data);
//  };

</script>
</html>

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.

Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft