1--TEST--
2swoole_socket_coro: reuse socket object
3--SKIPIF--
4<?php require __DIR__ . '/../include/skipif.inc'; ?>
5--FILE--
6<?php
7require __DIR__ . '/../include/bootstrap.php';
8
9const SEND_STR = "hello world\n";
10
11use SwooleTest\ProcessManager;
12
13$pm = new ProcessManager;
14$pm->parentFunc = function ($pid) use ($pm) {
15
16    echo "Co [1]\n";
17
18    $map = [];
19    Co\Run(function () use ($pm, &$map) {
20        $socket = new Swoole\Coroutine\Socket(AF_INET, SOCK_STREAM, 0);
21        Assert::assert($socket->connect('127.0.0.1', $pm->getFreePort()));
22        Assert::assert($socket->send(SEND_STR));
23        echo $socket->recv();
24        $map['sock'] = $socket;
25    });
26
27    echo "Co [2]\n";
28
29    Co\Run(function () use ($pm, &$map) {
30        $socket = $map['sock'];
31        Assert::assert($socket->send(SEND_STR));
32        echo $socket->recv();
33        unset($map['sock']);
34    });
35};
36
37$pm->childFunc = function () use ($pm) {
38    $socket = new Swoole\Coroutine\Socket(AF_INET, SOCK_STREAM, 0);
39    Assert::assert($socket->bind('127.0.0.1', $pm->getFreePort()));
40    Assert::assert($socket->listen(128));
41    $pm->wakeup();
42    go(function () use ($socket, $pm) {
43        $client = $socket->accept();
44        Assert::isInstanceOf($client, Swoole\Coroutine\Socket::class);
45        while (true) {
46            $client_data = $client->recv(1024, -1);
47            if (empty($client_data)) {
48                echo "closed\n";
49                break;
50            }
51            if ($client->errCode > 0) {
52                Assert::same($client->errCode, SOCKET_ETIMEDOUT);
53                break;
54            } else {
55                Assert::same($client_data, SEND_STR);
56                $client->send('swoole '.SEND_STR);
57            }
58        }
59        $client->close();
60        $socket->close();
61        echo "server exit\n";
62    });
63};
64
65$pm->childFirst();
66$pm->run();
67?>
68--EXPECT--
69Co [1]
70swoole hello world
71Co [2]
72swoole hello world
73closed
74server exit
75