Create a websocket server in php – ch studio

There is an increasing worldwide appetite for data delivered in real time, as both producers và consumers are more & more interested in faster experiences và instantaneous data transactions. In the context of realtime communication, WebSocket is the most popular transport protocol out there. Standardized in 2011 through RFC 6455, the WebSocket protocol paved the way lớn a truly realtime web. The protocol has known wide-spread adoption, và, nowadays, all major browsers support WebSockets. 

PHPhường. is an open-source, general-purpose scripting language that is especially suited for building web-based applications. Simple, efficient, & flexible, PHP. is compatible with most operating systems, such as Windows, Linux, và Unix, and it’s easy to lớn integrate with other technologies. 

There are many ways you can unlochồng the power of WebSockets in PHP.. For example, you can use Swoole, a networking framework that uses an event-driven, asynchronous, non-blocking I/O mã sản phẩm. Another example is Ratchet, a loosely coupled PHP.. library that enables you to build WebSocket-based apps. 

Since demand for realtime data is growing steadily, & with PHP being an established and popular programming language, I think it’s worth looking at some of the many challenges of implementing a reliable and highly-performant client-side WebSocket solution in PHP.

Bạn đang xem: Create a websocket server in php – ch studio

Copy links khổng lồ clipboardState of play — a brief overview

Rarely is a basic or raw WebSocket implementation enough for the needs of a realtime phầm mềm that services an unknown (but potentially very high) number of users. Most of the time, you need khổng lồ think about extending the capabilities of your PHP client-side WebSocket implementation. 

For this purpose, you could use an open-source library like php-websocket-client, which provides a simple WebSocket WAMPhường. client. This is how you use php-websocket-client:

use WebSocketClientWebSocketClient;use WebSocketClientWebSocketClientInterface;class Client implements WebSocketClientInterface private $client; public function onWelcome(array $data) public function onEvent($topic, $message) public function subscribe($topic) $this->client->subscribe($topic); public function unsubscribe($topic) $this->client->unsubscribe($topic); public function call($proc, $args, Closure $callback = null) $this->client->call($proc, $args, $callback); public function publish($topic, $message) $this->client->publish($topic, $message); public function setClient(WebSocketClient $client) $this->client = $client; $loop = ReactEventLoopFactory::create();$client = new WebSocketClient(new Client, $loop);$loop->run();
However, while it’s true that libraries like php-websocket-client offer some benefits, they are essentially just wrappers around a WebSocket client; they provide limited additional functionality.

To get the most out of WebSockets, a protocol that’s built on top is often used, which enables richer functionality, such as pub/sub. You could choose to develop your own WebSocket-based protocol that is tailored specifically to your needs. However, that is a very complex & time-consuming undertaking. Most of the time, you are better off using an established WebSocket-based solution that is well prepared khổng lồ handle an entire mix of engineering complexities. 

Here at, we have a protocol for pub/sub that is used on top of WebSockets. It allows you khổng lồ communicate over WebSockets by using a higher-cấp độ mix of capabilities. To demonstrate how simple it is, here’s how you create a client và a channel:

$client = new obatambeienwasirherbal.comobatambeienwasirherbal.comRest('your.appkey:xxxxxx');$channel = $client->channel('test');
And here's how you publish a message to lớn a channel:

$channel->publish('myEvent', 'Hello!'); // => true
As you can see from the code snippets above, although the communication is done over WebSockets, the underlying WebSocket protocol is ‘’hidden’’ from developers.

You can decide to use any WebSocket-based protocol that supports PHPhường. Regardless of your choice, though, you need to lớn consider the entire spectrum of challenges you’ll face when it comes lớn WebSockets. 

Copy liên kết to clipboardWebSockets và PHP: what you need lớn consider

Before we get started, I must emphakích cỡ that this article only focuses on the client-side challenges of building a dependable WebSocket-based solution for PHP apps. I assume you have already decided what solution you want to lớn use on the server-side. If you haven’t yet, you can go with an open-source library, or a cloud-based solution lượt thích

It’s also worth mentioning that I’ve sầu written this article based on the extensive sầu collective knowledge that the team possesses about the challenges of realtime communication via WebSockets.

I’m now going to lớn dive sầu into lớn the key things you need to lớn think about, such as authentication, network compatibility, or handling reconnections with continuity. Your client-side WebSocket implementation must be equipped to lớn efficiently handle all these complexities if you are lớn build a reliable system.

Copy link lớn clipboardDo you actually need WebSockets?

WebSocket is the most popular & portable realtime protocol. It provides full-duplex communication over a single TCPhường connection. WebSockets are a great choice for many use cases, such as financial tickers, chat solutions, or location-based apps, to name just a few. But it’s not the only available option. Before jumping on the WebSocket bandwagon, you should look at the existing alternatives, khổng lồ make sure they are not a better fit for your use case.

For example, MQTT, which also supports bidirectional communication, is the go-lớn protocol for IoT devices with limited battery life, & for networks with expensive sầu or low bandwidth, unpredictable stability, or high latency. Another example is Server-Sent Events, a lightweight protocol from both an implementation và usage standpoint. It’s a superior alternative sầu for most browser-based scenarios where unidirectional communication is enough, such as users subscribing to a basic news feed. 

WebSockets, MQTT, and SSE are all TCP-based protocols. TCP.. is designed lớn be a reliable transport layer protocol, which provides message delivery và ordering guarantees. This is great for many realtime use cases. But for other use cases, a lightweight, speedier protocol is a better option. For example, if your purpose is lớn stream video data, you’re better off using UDP as your transport layer protocol.

Even if WebSocket is a good choice for your needs, depending on the complexity of your architecture và what you are trying khổng lồ achieve sầu with your system, you might want lớn have the flexibility of using multiple protocols, one for each specific use case. 

At, we embrace open standards and interoperability, & we believe that you should have the flexibility to lớn choose the right protocol for the job at any given moment. That’s why we tư vấn WebSockets, SSE và MQTT, ahy vọng other options.

Learn more about the protocols supports

Copy liên kết to lớn clipboardAuthentication

Generally, it’s a good idea khổng lồ only allow authenticated users lớn use a WebSocket connection. However, a raw WebSocket request has no header, so you’re unable to provide authentication in the way you might with an HTTP request. That’s why you need lớn use another component or service for authentication. 

A client-side WebSocket library might be an option, but be careful when selecting one, as not all of them provide authentication mechanisms (or if they bởi vì, they can be quite limited). Alternatively, you can build your own authentication service. Most of the time, though, you are better off using a mature, feature-rich solution, such as a realtime messaging platkhung, that handles not only authentication, but an entire set of engineering complexities related lớn streaming data over WebSockets.

Let’s now look at the most comtháng authentication mechanisms you can use over WebSockets. The first one, basic authentication, is the simplest option available (and also the least secure) và it involves the use of API keys. The credentials are usually passed as a query parameter in a URL, which looks something lượt thích this:


From a security perspective, it’s recommended to lớn only use basic authentication server-side, because exposing an API key khổng lồ multiple clients is highly insecure. In theory, if you use ephemeral API keys that expire after a given amount of time on the client-side, you minimize the risk of them being compromised. However, in practice, a URL containing an ephemeral API key would be broken as soon as the key expires. In addition, request logging services would capture the API key in hệ thống logs. Therefore, you would have khổng lồ open a new WebSocket connection each time the API key is refreshed. This is not a scalable approach.

Token-based authentication is another widely-used authentication mechanism. One of the most popular methods of token-based authentication is called JSON Web Token (JWT). It’s an open và flexible format that has become an industry standard. At a basic cấp độ, JWTs work as illustrated in this diagram:


The client sends an authorization request to lớn the authorization hệ thống.

The authorization VPS returns an access token khổng lồ the client.

The client uses the access token lớn access a protected resource.

JWT is the recommended strategy on the client-side as it provides more fine-grained access control than basic authentication and limits the risk of exposed or compromised credentials. Furthermore, in addition khổng lồ JWTs being ephemeral by kiến thiết, they can also be revoked. 

While JWTs are obviously more reliable và secure than basic authentication, they come with some engineering challenges that you will have lớn manage if you decide to lớn develop your own JWT-based authentication solution:

How do you handle token privileges và permissions?

How bởi you set TTL (Time To Live)?

How bởi vì you renew tokens?

How are tokens sent? If it’s via URL, you need a mechanism that allows you to renew tokens when they expire, without starting a new WebSocket connection.

Xem thêm: Tải Game Ohay Win - ‎Ohay On The App Store

At, we provide two types of authentication mechanisms: basic auth (API keys), which we recommover lớn be used exclusively on the server-side, và token-based authentication, which supports both tokens and JWTs, and is ikhuyễn mãi giảm giá for the client-side. We handle all the complexity around renewing tokens and permission management through our client SDKs. 

Learn more about’s authentication mechanisms

Copy links to lớn clipboardNetwork compatibility and fallbachồng transports

Despite widespread platform tư vấn, WebSockets suffer from some networking issues. The main one is proxy traversal. For example, some servers và corporate firewalls block WebSocket connections.

Ports 80 và 443 are the standard ports for website access and they tư vấn WebSockets. lưu ý that port 80 is used for insecure connections. With that in mind, it’s recommended lớn use port 443 for WebSockets whenever possible, because it’s secure, và prevents proxies from inspecting the connections. If you have sầu to (or wish to) run WebSockets on different ports, network configuration is usually needed. 

That said, if you can’t use port 443 and you foresee clients connecting from within corporate firewalls or otherwise tricky sources, you might need to tư vấn fallbaông chồng transports such as XHR streaming, XHR polling, or JSONPhường polling. That’s why you need to use a client-side WebSocket-based solution that supports fallbacks. This solution can take various forms; you can opt for an open-source library designed specifically to lớn provide lots of fallbachồng capabilities, such as SockJS. 

Alternatively, you can build your own complex fallbaông xã capability, but the scenarios where you actually have sầu lớn are very rare. Developing a custom solution is a complex process that takes a lot of time & effort. In most cases, to lớn keep engineering complexity to a minimum, you are better off using an existing WebSocket-based solution that provides fallbaông chồng options.’s aim has always been to lớn provide a reliable, scalable, và highly-performant realtime pub/sub messaging service. Because of our service aims, we wanted lớn provide guarantees around message ordering and delivery. The raw WebSocket transport doesn’t solve sầu this out-of-the-box. That’s why we made the decision lớn build our own protocol on top of WebSockets, which also include fallbacks, among mỏi other features and benefits.

Learn more about:

Copy liên kết lớn clipboardDevice power management và heartbeats

By its very nature, a WebSocket connection is persistent. This also means it’s consuming battery life for as long as it’s active sầu. With WebSockets enjoying support across various programming languages and development frameworks, including PHPhường, device power management is something essential to consider. Unfortunately, it’s not handled by many PHP WebSocket libraries.

There are several ways you can approach battery management và heartbeats. The WebSocket protocol natively supports control frames known as Ping and Pong. This is an application-cấp độ heartbeat mechanism that allows you to lớn detect whether a WebSocket connection is alive. Usually, the server-side sends a Ping frame and, on receipt, the client-side sends a Pong frame baông chồng to the server.

You could theoretically also use protocol-cấp độ heartbeats — TCP keepalives. However, this is a less than ideal option, as TCPhường keepalives don’t get past web proxies. In other words, with TCP keepalives, you can’t always verify a connection end-to-over. 

Be aware that the more heartbeats you sover, the faster battery is depleted. This can be quite problematic, especially when Mobile devices are involved. In these scenarquả táo, to lớn preserve sầu battery life, you may want to use OS-native push notifications where possible. With this approach, there’s no need to maintain a WebSocket connection active sầu, because the VPS can wake up an inactive sầu instance of your tiện ích whenever you sover a push notification. 

While push notifications are a great choice for waking up an phầm mềm, they are not a replacement for a WebSocket or streaming protocol layer, because they vày not provide quality of service guarantees. Push notifications are typically ephemeral, have variable latencies, & aren’t ordered. Furthermore, there is usually a limited number of push notifications that can be queued up for delivery at any given moment.

Before deciding whether lớn use heartbeats, push notifications, or both, you must carefully analyze your system requirements & use cases. For example, if you’re developing a chat solution or a multiplayer game, you want khổng lồ send frequent heartbeats, even if that means battery life is depleted faster. On the other hand, if you are developing an online siêu thị và want khổng lồ infrequently notify customers about new products, you might want to lớn use push notifications for this specific purpose. Push notifications will better preserve battery life, even if it means that your connection status detection will not be as accurate.

At, we believe that you should always have the flexibility khổng lồ decide whether you want khổng lồ use heartbeats, push notifications, or both, depending on the specifics of your use case(s). That’s why we provide a heartbeat functionality, as well as native push notifications. 

Learn more about:

Copy link lớn clipboardHandling reconnections with continuity

It’s comtháng for devices to experience changing network conditions. Devices might switch from a di động data network to lớn a Wi-Fi network, go through a tunnel, or perhaps experience intermittent network issues. Abrupt disconnection scenartiện ích ios lượt thích these require a WebSocket connection lớn be re-established.

For some realtime use cases, resuming a stream after disruption precisely where it left off is essential. Think about features lượt thích live chat, where missing messages during disconnection cause confusion & frustration. You need to ensure that your client-side WebSocket implementation is equipped to handle complexities around reconnections. The implementation should also provide the means lớn resume a stream and offer exactly-once delivery guarantees.

If resuming a stream exactly where it left off after brief disconnections is important to your use case, you need khổng lồ implement history / persisted data. Getting inkhổng lồ the detail of this is out of the scope of this article (see this blog post for more), but these are some things you’ll need khổng lồ consider:

Caching messages in front-end memory. How many messages vị you store và for how long?

Moving data khổng lồ persistent storage. Do you need to lớn move sầu data to disk? If so, how long vì chưng you store it for? Where bởi vì you store it? And how will clients access that data when they reconnect?

Resuming a stream. When a client reconnects, how vì you know which stream to resume và where exactly to resume it from? Do you need to lớn use a connection ID lớn establish where a connection broke off? Who needs khổng lồ keep traông xã of the connection breaking down - the client, or the server?

Backoff mechanism. What is your incremental backoff strategy? How bởi you prevent your servers from being overloaded in scenartiện ích ios where you have a high number of clients that keep trying (and failing) lớn reestablish a connection?

You might even consider whether WebSockets is what you truly need. If your use case doesn’t require bidirectional messaging, but subscribe-only, then a protocol lượt thích SSE with stream resume baked in might be a better choice. 

The platform enables clients to lớn resume a stream exactly where it left off. We’ve sầu developed this resume capability in such a way that it provides an exactly-once message delivery guarantee, rather than the inferior at-least-once or at-most-once guarantees. To achieve sầu this, all our client SDKs are equipped lớn keep traông chồng of the last message that was received by a client. If a disconnection occurs, when the client is back và the connection is restored, it notifies our servers of the last message it has received. 

Our resume capability allows clients that experience transient network failures lớn reconnect & resume a stream within two minutes. However, messages can still be retrieved even in the case of long-term disconnections (e.g. a day). For this purpose, we provide a history API. 

Learn more about:

Copy liên kết to clipboardFinal thoughts

Hopefully, this article has shown you what khổng lồ expect when implementing a client-side WebSocket-based solution in PHPhường. Raw WebSockets will rarely be enough, even for simple use cases. If you want to lớn scale your system & provide optimum experiences for end-users, you will most likely have sầu lớn use a feature-rich WebSocket solution.

At, we’ve developed an enterprise-ready pub/sub messaging platform that makes it easy khổng lồ efficiently thiết kế, quickly ship, và seamlessly scale critical realtime functionality delivered directly to lớn end-users. We have also developed our very own WebSocket-based protocol, but we also tư vấn raw WebSockets, & other protocols, like SSE or MQTT. 

Our platkhung is designed in a manner that enables PHPhường developers khổng lồ offload hard engineering and infrastructure problems to, so they can focus entirely on building their products. That’s why we offer 25+ client-side SDKs, PHP. included.

If you want khổng lồ talk more about WebSockets or if you’d lượt thích lớn find out more about and how we can help you in your PHPhường & WebSockets journey, get in touch or sign up for a free account.

We’ve written a lot over the years about realtime messaging and topics such as WebSockets. Here are some useful links, for further exploration: