简体   繁体   中英

Send data from PHP Client to PHP Webserver Socket

I need to send some data to my websocket server in one way (something like push notification message) from PHP Client, but I have problems to do that.

The PHP websocket server works properly, if I open multiple tabs from the browser then the server is able to receive and send messages, but I have another micro service in PHP and now I want to send push notification to the websocket server using PHP but I don't know how can do that.

Thw websocket server is runned on ws://0.0.0.0:8020

I'm trying something like this:

<?php
$host    = "localhost";
$port    = 8020;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Fail1\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Fail2\n");
var_dump($socket);
var_dump($result);
?>

ps The PHP websocket server and PHP client are on the same machine, I tried also with interprocess socket but with no luck.

Finally, I found the solution, here is my final working code:

<?php

$host    = "localhost";
$port    = 8020;

$context = stream_context_create();

$socket = @stream_socket_client(
    $host . ':' . $port,
    $errno,
    $errstr,
    30,
    STREAM_CLIENT_CONNECT,
    $context
);

$key = generateWebsocketKey();
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Key: $key\r\n\r\n";
stream_socket_sendto($socket, $headers);
stream_socket_sendto($socket, 'this is my socket test to websocket');

function generateWebsocketKey() {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$&/()=[]{}0123456789';
    $key = '';
    $chars_length = strlen($chars);
    for ($i = 0; $i < 16; $i++) $key .= $chars[mt_rand(0, $chars_length-1)];
    return base64_encode($key);
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM