简体   繁体   English

尝试打印从更多客户端收到的消息时出现问题

[英]Problem when trying to print messages received from more clients

Let me explain the problem: I'm creating a system that use sensors able to read some data, then, each sensor, will have to send those data to a server that will print each message received in a new line on the page. 让我解释一下问题:我正在创建一个使用能够读取一些数据的传感器的系统,然后每个传感器都必须将这些数据发送到服务器,该服务器将在页面上的新行中打印收到的每条消息。

Sensor.php Sensor.php

class Sensor extends Thread implements ISensor
{
    ....

    public function readValue(){
        $this->value = rand( -15 , 40 );
        $this->timestamp = date('Y-m-d H:i:s');
    }

    public function run(){
        $number = 0;
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Couldn't create socket");
        $this->connectionResult = socket_connect($this->socket, $this->ip, (int)$this->port) or die("Couldn't connect to server");
        while($number <= $this->requestNumber){
            $number = $number + 1;
            $this->readValue();
            $this->sendData();
            sleep($this->frequency);
        }
        socket_close($this->socket);
    }

    public function sendData(){
        $input = $this->toString();
        socket_write($this->socket, $input, strlen($input)) or die ("Impossible send message");
    }

Server.php Server.php

set_time_limit (300);
$address = '127.0.0.1';
$port = 19000;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $address, $port) or die('Could not bind to address');
socket_listen($sock);

while (true) {
    $client = socket_accept($sock);
    while (0 != socket_recv($client, $message, 1024, 0))
    {
        echo $message . "<br>";
    }
    socket_close($client);
}
socket_close($sock);

The expected result was that the clients are able to connect to the server and send messages (this works fine) while the server just print a new line for each message received. 预期的结果是,客户端能够连接到服务器并发送消息(这很好),而服务器只是为收到的每条消息打印新行。

That partially works, I will explain better with a screenshot (I'm actually unable to post screenshot, I will leave a link to the screenshot image if you can't understand the problem with the text description under) 那部分起作用,我将用屏幕截图更好地解释(我实际上无法发布屏幕截图,如果您无法理解下面的文字说明问题,我将留下指向屏幕截图图像的链接)

在此处输入图片说明

The first sensor keep sending all the messages and the server print them corretly then, when the thread ends, the server just output a whole line of all the messagges received from the second second sensor while the first was still running and then print the messages like it should. 第一个传感器继续发送所有消息,服务器正确地打印它们,然后,当线程结束时,服务器仅输出第二个第二个传感器接收的所有消息的整行,而第一个传感器仍在运行,然后像这应该。

It's because of the while loop? 是因为while循环? If I remove the while loop the server just print one single message for each sensors. 如果删除while循环,则服务器仅为每个传感器打印一条消息。

I have actually found the solution. 我实际上找到了解决方案。

After hours and hours of web searching i finally found the correct keywoard that showed me a page with this code 经过数小时的网络搜索,我终于找到了正确的密码,向我显示了包含此代码的页面

ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

// Set time limit to indefinite execution
set_time_limit(0);

// Set the ip and port we will listen on
$address = '127.0.0.1';
$port = 15000;

//Implicit Flush
ob_implicit_flush();

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');

// Start listening for connections
socket_listen($sock);

// Non block socket type
socket_set_nonblock($sock);

// Clients
$clients = [];
// Loop continuously
while (true) {
    // Accept new connections
    if ($newsock = socket_accept($sock)) {
        if (is_resource($newsock)) {
            // Set Non-block for the new connection
            socket_set_nonblock($newsock);
            // Append the new connection to the clients array
            $clients[] = $newsock;
        }
    }
    // Polling for new messages
    if (count($clients)) {
        foreach ($clients AS $k => $v) {
            // Check for new messages
            $string = '';
            if ($char = socket_read($v, 1024)) {
                $string .= $char;
            }
            // New string for a connection
            if ($string) {
                echo "$string <br>";
            } else {
                if ($seconds > 30) {
                    // Ping every 5 seconds for live connections
                    if (false === socket_write($v, 'PING')) {
                        // Close non-responsive connection
                        socket_close($clients[$k]);
                        // Remove from active connections array
                        unset($clients[$k]);
                    }
                    // Reset counter
                    $seconds = 0;
                }
            }
        }
    }
    sleep(1);
    $seconds++;
}
// Close the master sockets
socket_close($sock);

And works perfectly! 并完美地工作!

Thanks guys for the help, i post the auto-anwser in case someone else is having a similar issue. 谢谢大家的帮助,如果有人遇到类似问题,我会发布自动答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM