我的目标:在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变量)转换为字节字符串?
答案 0 :(得分:1)
以下是如何进行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