swoole / swoole-src

🚀 Coroutine-based concurrency library for PHP
https://www.swoole.com
Apache License 2.0
18.4k stars 3.16k forks source link

[QUESTION] how to add Swoole\Client to the eventLoop #4143

Closed sauriio closed 3 years ago

sauriio commented 3 years ago

Please answer these questions before submitting your issue. Thanks!

  1. What did you do? If possible, provide a simple script for reproducing the error. I'm trying to make an async client from the Swoole\Client, i couldn't make it work on coroutines because i don't really know how to reuse the same connection and to maintaint it persistent on the client object on multiple coroutines calls, sometimes i need to make wait for response while i'm writing to the socket, i manage to add that logic on the timer and then I call the swoole_client_select to see if there is a posibility to read/write, but then I read that you can add some fds to the eventLoop, can you make some some examples on read/write with it.

  2. What did you expect to see? [QUESTION]

  3. What did you see instead? [QUESTION]

  4. What version of Swoole are you using (show your php --ri swoole)? 4.6.4

  5. What is your machine environment used (show your uname -a & php -v & gcc -v) ?

php 7.4

matyhtf commented 3 years ago

Example

use Swoole\Client;
use Swoole\Event;

$fp = new Client(SWOOLE_SOCK_TCP);
$fp->connect('www.qq.com', 80);

Event::add($fp, function($fp) {
    $resp = $fp->recv(8192);
    Assert::contains($resp, 'Location: https://www.qq.com/');

    swoole_event_del($fp);
    $fp->close();

    echo "Done\n";
});

Event::write($fp, "GET / HTTP/1.1\r\nHost: www.qq.com\r\n\r\n");
Event::wait();