如何以编程方式(使用PHP)调用WebSocket? [英] How to call a WebSocket programmatically (using PHP)?
问题描述
我遇到一种情况,我需要根据另一个浏览器的输入来更新一个浏览器窗口.现在,我正在使用WebSockets,并且效果很好.
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.
现在,我想使用PHP而不是浏览器将数据发送到WebSocket(因此,使用ws://代替ws://).换句话说,我想使用PHP而不是JavaScript模拟WebSocket.send()调用.
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.
我有以下似乎无效的代码(未调用onmessage):
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
}
推荐答案
操作方法如下:
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);
这篇关于如何以编程方式(使用PHP)调用WebSocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!