Skip to content
Advertisement

WebSockets – send json data via php

I’m trying to send a fire-and-forget request from PHP to my websocket aws api gateway.

I’ve set up an action called “sendmessage”.

This is the code I’m using:

JavaScript

However, nothing happens.

If I use wscat, like:

JavaScript

it works just fine.

What am I doing wrong in my php code?

Note: I need the socket connection to be persistent (the way it is when using the pfsockopen function).

Advertisement

Answer

Since you didn’t provide a handpoint link, here is some notes, following own tests!

I guess the issue comes from the wss part, php needs to retrieve the certificate first, so it can encrypt the data.

Your code should work just fine on a ws:// stream.

To connect to a regular ws:// stream, one can simply use fsockopen().

JavaScript

But to connect to a wss:// secure websocket stream, using php, without libraries, we need to create a tunnel first, by querying the public key with stream_socket_client.

This is a handshake mechanism. This can be done as follow.

Notice the first ssl:// call. This is the TLS 1.0 protocol.

JavaScript

The output should looks like:

JavaScript

Same base code, another example, pulling data from Binance wss:// stream.

We can also use TLS 1.2, with a tls:// handshake instead. Works on most servers.

JavaScript

Here is a way to retrieve only the ssl RSA public key of a remote handpoint, from php. Can be used to speed up later connections.

JavaScript

Output something like:

JavaScript

There is possibly other quircks, to be sure, we need the main handpoint^. Would be glad to test that. Otherwise good luck, there is a big lack of documentation on the subject.

This is still a new born protocol (2011!). Best details are in the RFC specification:

The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011

About the handshake, it must be initiated by a GET request.

The client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET)

Writing_WebSocket_servers#Client_handshake_request


In short:

If unencrypted WebSocket traffic flows through an explicit or a transparent proxy server without WebSockets support, the connection will likely fail.

WebSocket#Proxy_traversal

Transport_Layer_Security#Digital_certificates

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement