Home Backend Development PHP Tutorial Implementing PHP and websocket chat room based on Swoole_php example

Implementing PHP and websocket chat room based on Swoole_php example

Aug 17, 2016 pm 01:02 PM

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

//创建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();

Copy after login

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

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

Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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

See all articles