【发布时间】:2019-08-01 08:39:25
【问题描述】:
我正在尝试使用 PHP 通过 TCP 套接字将我的 MYSQL 选择查询的结果发送到我的 Rpi 服务器。
这是 PHP 代码:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "fyp_lora";
$host = "localhost";
$port = 12345;
$f = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($f, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec'
=> 500000));
$s = socket_connect($f, $host, $port);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM led_control";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
echo $row["ID"]. ",". $row["LED"]. "," . $row["Status"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
foreach($data as $value)
{
$msg= $value["ID"]. ",". $value["LED"]. "," . $value["Status"] . "<br>";
$len = strlen($msg);
while (true) {
print($msg);
$sent = socket_write($f, $msg, $len);
if ($sent === false) {
break;
}
// Check if the entire message has been sent
if ($sent < $len) {
// If not send the entire message.
// Get the part of the message that has not yet been sent as message
$msg = substr($msg, $sent);
// Get the length of the not sent part
$len -= $sent;
} else {
socket_close($f);
break;
}
}
}
?>
</body>
</html>
以下是引用的python代码: Sending a message from PHP to Python through a socket
import socket
s = socket.socket()
host = "localhost"
port = 12345
s.bind((host, port))
s.listen(5) #allows for 5 connections to be established
while True:
c, addr = s.accept()
data = c.recv(1024)
if data: print (str(data.decode().split(",")))
c.close() #closes the socket
在 Rpi 服务器上,它只会接收第一行消息,例如:['1', 'LED 1', 'OFF'] 但它不会接收其余的消息。
完整的消息如下:
1,LED 1,关闭
2,LED 2,关闭
3,LED 3,关闭
4,LED 4,开
我将不胜感激任何帮助:)
【问题讨论】:
标签: php html mysql python-3.x websocket