我的目标:在php中发送UDP广播消息。消息必须是字节字符串。
这是我的测试代码
const TIMEOUT = 5;
const PORT = 8888;
const IP = "255.255.255.255";
const STR = "test";
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>TIMEOUT,"usec"=>0));
socket_sendto($sock, STR, strlen(STR), 0, IP, PORT);
//wait the responses for TIMEOUT sec
while(true) {
$ret = @socket_recvfrom($sock, $buf, 20, 0, $ipDevice, $portDevice);
if($ret === false) break;
echo "-".$buf." - ".$ipDevice.":".$portDevice . "<br>";
}
socket_close($sock);
但是socket_sendto需要一个字符串参数来发送(我的STR变量)。
所以问题是:我如何将字符串(我的STR变量)转换为字节字符串 ?
如何创建UDP广播:
<?php
$broadcast_string = "test";
$port = 1234;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
socket_close($sock);
?>
编辑:下面是如何将string
转换为字节串:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] since values are range of 0 - 255