Core concepts
HTTP Requests
In OpenSwoole, WebSockets extends the HTTP Server.
Customizing the Conveyor Server
The Conveyor Server offers several customization points, allowing you to add an HTTP handler to manage HTTP requests and serve your website or any HTTP interface.
In this example, we utilize the Conveyor Server Events to customize the server behavior. For more information on Conveyor Server Events, you can refer to the Conveyor Server Events.
Adding an HTTP Handler
Option 1:
The following example demonstrates how to add an HTTP handler using the Conveyor Server and OpenSwoole:
1<?php
2
3use Conveyor\ConveyorServer;
4use OpenSwoole\Http\Request;
5use OpenSwoole\Http\Response;
6use Conveyor\Events\PreServerStartEvent;
7
8$listeners = [
9 ConveyorServer::EVENT_PRE_SERVER_START => fn (PreServerStartEvent $event) =>
10 $event->server->on('request', function (Request $request, Response $response) {
11 $response->end('Hello World!');
12 }),
13];
14
15(new ConveyorServer())
16 ->eventListeners($listeners)
17 ->start();
In this example:
- We use the
ConveyorServer::EVENT_PRE_SERVER_START
event to set up a listener that handles HTTP requests. - The event listener is defined using a closure that takes a
PreServerStartEvent
object. - Inside the event listener, we attach a handler to the server's
request
event, which sends a "Hello World!" response to incoming HTTP requests.
This setup allows the Conveyor Server to handle HTTP requests and respond accordingly, enabling you to serve web content or create custom HTTP interfaces.
The tradeoff of the option 1 is that it prevents broadcasting from happening via HTTP since it intercepts from the very beginning of the http handling functionality. Broadcasting is a feature available in Conveyor to send messages to specific channels via HTTP, see more here: Broadcasting Messages to Channels via HTTP Requests.
Option 2:
1<?php
2
3include __DIR__ . '/vendor/autoload.php';
4
5use Conveyor\Constants;
6use Conveyor\ConveyorServer;
7use OpenSwoole\Http\Request;
8use OpenSwoole\Http\Response;
9use Hook\Filter;
10
11Filter::addFilter(
12 Constants::FILTER_REQUEST_HANDLER,
13 fn() => fn(Request $request, Response $response) => $response->end('Hello World!'),
14);
15
16(new ConveyorServer())->port(9501)->start();
In this example:
- We use the Filter Hook
Constants::FILTER_REQUEST_HANDLER
to set up a callback that handles HTTP requests. - The callback takes a
Request
andResponse
object and sends a "Hello World!" response to incoming HTTP requests.
The option 2 allows the broadcasting to happen via HTTP since it is not intercepting the http handling functionality.
Refer to this part of the documentation if you want to know how to broadcast Messages to Channels via HTTP Requests.