How to use PubSub from a PHP client

Hi everyone.

I have a PHP client for testing PubSub service but I can’t get it to work. Server always returns me a “400 Bad Request” response. Same example works for me in Javascript.

“Reply From Server :HTTP/1.1 400 Bad Request Server: awselb/2.0 Date: Thu, 27 Aug 2020 19:12:28 GMT Content-Type: text/html Content-Length: 138 Connection: close”

My code is:

$host = "pubsub-edge.twitch.tv";
$ip = gethostbyname($host);
$port = 443;
$message = '{"type":"LISTEN","nonce":"tO4XRdd9RM1u88B","data":{"topics":["video-playback-by-id.92205927"],"auth_token":"XXXXXXXXXXXXXXXXXXX"}}';
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $ip, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);

I know “video-playback-by-id” is an undocumented topic and I shouldn’t use it, but only it’s for test and works in Javascript.

Thanks in advance.

Best regards.

Websockets are not raw TCP, which is what you’re doing there with the socket_ calls. You’re missing the entire websocket handshake and protocol wrapping.

1 Like

Thank you very much!. I’m trying to find some Websocket PHP library. Any suggestion is welcome.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.