Home Backend Development PHP Tutorial How to use WebSocket in PHP?

How to use WebSocket in PHP?

May 12, 2023 am 08:27 AM
php websocket websocket server websocket client

As web applications become more complex, real-time communication and data push are becoming more common. This is where WebSocket comes in. WebSocket is a protocol that allows servers and clients to establish persistent connections for two-way communication for real-time communication and data push. In this article, we will discuss how to use WebSocket in PHP.

  1. Introduction to WebSocket Protocol

WebSocket is a full-duplex, TCP-based protocol that allows the server and client to communicate in real time after a connection is established. Unlike the HTTP request-response model, a WebSocket connection always remains open after the connection is established, so multiple HTTP handshakes are not required.

WebSocket is a binary protocol that supports multiple data types, including text, binary, JSON, XML, etc. This makes WebSocket ideal for real-time communication and data pushing.

  1. Install WebSocket library

Using WebSocket in PHP requires the use of a library. In this article, we will use the Ratchet library. To install Ratchet, you can run the following command through Composer:

composer require cboden/ratchet
Copy after login

After the installation is complete, we can start writing code to implement the WebSocket application.

  1. Implementing WebSocket Service

The following is a simple example for implementing a WebSocket service that will receive a message from the client and send the message to All connected clients:

use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New client connected: {$conn->resourceId}
";
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Client disconnected: {$conn->resourceId}
";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($client !== $from) {
                $client->send($msg);
            }
        }
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "Error: {$e->getMessage()}
";
        $conn->close();
    }
}

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);

echo "Server started
";
$server->run();
Copy after login

In the above example, we defined a class called Chat, which implements the MessageComponentInterface interface. This class contains special methods for handling connections, disconnections, and messages from clients.

onOpen(ConnectionInterface $conn): This method is called when the client connects to the server. Here we add the connection to the client object.

onClose(ConnectionInterface $conn): This method is called when the client closes the connection. Here we delete the connection client object.

onMessage(ConnectionInterface $from, $msg): This method is called when the client sends a message. Here we send messages to other connected clients.

onError(ConnectionInterface $conn, Exception $e): This method is called when an error occurs. We close the connection here.

In the above example, we also created an HTTP server through the IoServer class, listening to port 8080, passing the request to the WebSocket server through HttpServer, and passing the request to the Chat class through WsServer.

  1. Implementing the client

To connect to our WebSocket server, you need to implement a client. Here is a simple example for connecting to a server and sending messages to it:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket client</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="message" placeholder="Enter your message">
    <button id="send">Send</button>

    <ul id="messages"></ul>

    <script>
        $(function () {
            var socket = new WebSocket('ws://localhost:8080');

            socket.onopen = function() {
                console.log('Connection opened');
            };

            socket.onclose = function() {
                console.log('Connection closed');
            };

            socket.onmessage = function(event) {
                var data = JSON.parse(event.data);
                $('#messages').append($('<li>').text(data.message));
            };

            $('#send').click(function() {
                var message = $('#message').val();
                socket.send(JSON.stringify({message: message}));
            });
        });
    </script>
</body>
</html>
Copy after login

In the above example, we create a new WebSocket connection using the WebSocket object. When a connection is opened or closed, the onopen and onclose events are triggered. When a WebSocket receives a message from the server, the onmessage event is triggered. We used the jQuery library to listen to the click event of the Send button, and when clicked, we sent the value of the text input box as a message to the server.

  1. Summary

WebSocket is a powerful protocol that allows the server and client to establish a persistent connection for two-way communication in order to achieve real-time communication and data push. In this article, we implemented a simple WebSocket server using the Ratchet library. We also used a simple HTML page to demonstrate how to connect to the server and send messages. If you want to build a real-time, interactive web application, then WebSocket is an absolutely indispensable part.

The above is the detailed content of How to use WebSocket in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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)

PHP asynchronous coroutine development practice: building a high-performance Websocket server PHP asynchronous coroutine development practice: building a high-performance Websocket server Dec 02, 2023 pm 12:21 PM

With the development of the Internet and the continuous advancement of technology, more and more applications require real-time communication, and Websocket technology has emerged as the times require. The Websocket protocol can realize two-way communication between the browser and the server, greatly improving the real-time performance of the server pushing data to the client, and providing good support for real-time applications. In the development of Websocket servers, PHP, as a common programming language, has attracted more and more attention from developers in terms of asynchronous coroutine development. What is PHP different

PHP WebSocket development example: demonstration of how to implement specific functions PHP WebSocket development example: demonstration of how to implement specific functions Sep 12, 2023 am 08:29 AM

PHP WebSocket development example: Demonstration of how to implement specific functions WebSocket is a protocol for real-time two-way communication, which makes it possible to establish a persistent connection between the client and the server. WebSocket is a powerful tool for web applications that need to implement real-time functionality or instant communication. In this article, we will demonstrate how to develop using PHPWebSocket and implement specific functions. Preparing the environment Before starting, make sure you have PH installed

How to use PHP multi-threading to implement a high-performance Websocket server How to use PHP multi-threading to implement a high-performance Websocket server Jun 30, 2023 pm 02:58 PM

How to use PHP multi-threading to implement a high-performance Websocket server Preface: With the continuous development of the Internet, real-time data transmission and interaction have become essential functions for many Web applications. In traditional Web development, the HTTP protocol is often used for communication between the client and the server. However, the HTTP protocol has the characteristics of stateless and request-response mechanisms, which cannot meet the needs of real-time data transmission. Websocket is a full-duplex communication protocol that can communicate between the client and the client in real time.

How to develop and implement PHP WebSocket functions? How to develop and implement PHP WebSocket functions? Sep 12, 2023 am 11:13 AM

How to develop and implement the functions of PHPWebSocket? Introduction WebSocket is a modern communication protocol that enables the establishment of persistent, real-time, two-way communication connections between clients and servers. Compared with the traditional HTTP protocol, WebSocket can provide lower latency and higher performance. This article will introduce how to use PHP to develop and implement WebSocket functions, so that you can use WebSocket to implement real-time communication functions in your own applications. Make sure the server supports

Getting Started Guide to PHP WebSocket Development: Analysis of Steps to Implement the Barrage Function Getting Started Guide to PHP WebSocket Development: Analysis of Steps to Implement the Barrage Function Sep 12, 2023 am 10:45 AM

Getting Started Guide to PHP WebSocket Development: Analysis of Steps to Implement the Barrage Function Introduction: With the development of the Internet, the need for real-time communication is becoming more and more urgent. WebSocket technology emerged as the times require, providing convenience for real-time communication. In this article, we will use PHP language to implement a simple barrage function to help readers get started with WebSocket development and understand the basic steps to achieve real-time communication. 1. What is WebSocket? WebSocket is a method in a single T

How to use PHP WebSocket development function to implement real-time message push on web pages How to use PHP WebSocket development function to implement real-time message push on web pages Sep 11, 2023 am 10:48 AM

How to use the PHP WebSocket development function to implement real-time message push on web pages. With the rapid development of the Internet, real-time communication has become an indispensable part of web applications. In the past, communication between web pages and servers was achieved by the client continuously sending requests to the server. This method was inefficient and also put greater pressure on the server. Using WebSocket technology, the server can actively push messages to the client, allowing web applications to receive and display the latest information in real time.

Introduction to PHP multi-threaded programming: Create a WebSocket server using the swoole extension Introduction to PHP multi-threaded programming: Create a WebSocket server using the swoole extension Jun 29, 2023 am 11:06 AM

Introduction to PHP multi-threaded programming: Creating a WebSocket server using the swoole extension Preface In Web development, real-time communication has become an increasingly important requirement. The traditional HTTP protocol cannot meet the needs of real-time communication, and the WebSocket protocol has become the solution. In order to implement a WebSocket server in PHP, we can use the swoole extension to create a multi-threaded server. 1. What is swoole? swoole is a PHP extension that provides

PHP WebSocket Development Guide: Analysis of Steps to Implement Key Functions PHP WebSocket Development Guide: Analysis of Steps to Implement Key Functions Sep 11, 2023 pm 07:25 PM

PHP WebSocket Development Guide: Analysis of Steps to Implement Key Functions With the continuous development of Internet applications, WebSocket, as a real-time communication protocol, has become an important tool in Web development. In the field of PHP, real-time chat, push notifications and other functions can be realized by using WebSocket. This article will introduce in detail how to use PHP to develop WebSocket applications and provide step-by-step analysis of some key functions. 1. Introduction to WebSocket WebSocket is

See all articles