How to call a WebSocket programmatically (using PHP)?
Solution 1
Here's how it's done:
http://permalink.gmane.org/gmane.comp.lang.javascript.nodejs/18088
$host = 'localhost'; //where is the websocket server
$port = 9000;
$local = "http://localhost/"; //url where this script run
$data = 'hello world!'; //data to be send
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
//WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000); //receives the data included in the websocket package "\x00DATA\xff"
fclose($sock);
Solution 2
In order to send data to the socket, you need to use fsockopen to open the connection to the socket at specified port. If the connection is successfully, all you need to do is use fwrite
However, you are going to be sending the data to the WebSocket server. The server will treat you as a client, and since you are not providing HTTP headers it expects for successful authentication - your connection will be refused.
Since you didn't say who is supposed to receive the message you are trying to send (all users or a specific user or something entirely different), without knowing what your goal is - it's hard to explain any further what you should do.
Nightwolf
Updated on July 19, 2022Comments
-
Nightwolf almost 2 years
I have a situation where I need to update one browser window based on input from the other. Right now I'm using WebSockets and it's working great.
Now I want to send data to the WebSocket using PHP instead of the browser (so instead of ws://, use PHP code). In other words, I want to simulate the WebSocket.send() call using PHP instead of JavaScript.
I have the following code which doesn't seem to work (the onmessage is not being called):
if ( function_exists('socket_create') AND $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) AND $sock_data = socket_connect($sock, "127.0.0.1", 12345) ) { $msg = "hello world"; $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set $sock_data = socket_write($sock, $msg, strlen($msg)); //Send data socket_close($sock); //Close socket }
-
Nightwolf about 13 yearsThanks, I'm actually using phpwebsocket already as the server. Will just try to copy the code from there to get it work. Thought it was simpler than that since I'm just sending one "packet" of data and that's it.
-
Ghedipunk almost 9 yearsReason for downvote: stackoverflow.com/help/how-to-answer -- Specifically "Answer the question" and "Provide context for links"