2
votes

I've installed the following git: Flynsarmy/PHPWebSocket-Chat on my server, and successfully set up the chat, it works fine, and users can communicate with each other well.

Last 24 hours i tried sending a System message from another php file:

$host = '89.163.140.48';  //where is the websocket server
$port = 9300;
$local = "http://www.indiamea.com";  //url where this script run
$data = '{"message":"TEST - MESSAGE - TEST"}';  //data to be send

$head = "GET /?token=$jwt HTTP/1.1"."\r\n".
            "Upgrade: WebSocket"."\r\n".
            "Connection: Upgrade"."\r\n".
            "Origin: $local"."\r\n".
            "Host: $host:$port"."\r\n".
            "Sec-WebSocket-Key: Bom4DUh5Brl8xmvUYbDQzA=="."\r\n".
            "Sec-WebSocket-Version: 13"."\r\n".
            "Content-Length: ".strlen($data)."\r\n"."\r\n";

//WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 15);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, $data ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);  //receives the data included in the websocket package "\x00DATA\xff"
fclose($sock);

Websocket is accepting the request (open event), but the message event is not fired inside the server.php script, which means that message is not sent to users.

I tried googling, but i couldn't find any solution.

I really hope that someone can help me with this.

If server.php code is required, you can acess it here: https://github.com/Flynsarmy/PHPWebSocket-Chat/blob/master/server.php

1
Maybe someone knows an alternative how can i simulate to send a message to websocket, so i can send System Messages in my chat?Ruslan Dascal

1 Answers

0
votes

You can't do what you're trying to do directly.

You can do it indirectly though – I've done this before commercially and the solution we went with was database polling.

So what you do is you create a loop in the websocket server when it starts, which runs every few seconds (say 10 seconds) to check a database table for messages flagged as unsent. If it finds one then it sends it and flags it as sent.

Your PHP backend can write to this table of course, so the database acts as a mediator between your websocket client/server and your PHP back-end.

However if your websocket server is already running a while loop then this won't be possible without a separate thread.