《就是要你懂Swoole》--package_eof的一个小细节

有的同学在开启了Swoole\Serverpackage_eof的时候,发现并没有生效。Server端的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

$serv = new Swoole\Server('127.0.0.1', 9501);

$serv->set(array(
'worker_num' => 4,
'package_eof' => "\r\n\r\n",
'open_eof_check' => 1,
));

$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.\n";
});

$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
$serv->send($fd, 'Swoole: '.$data);
$serv->close($fd);
});

$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});

$serv->start();

Client端的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

$client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

$client->on("connect", function(swoole_client $cli) {
$cli->send('hello world\r\n\r\n');
});

$client->on("receive", function(swoole_client $cli, $data){
echo "Receive: $data";
});

$client->on("error", function(swoole_client $cli){
echo "error\n";
});

$client->on("close", function(swoole_client $cli){
echo "Connection close\n";
});

$client->connect('127.0.0.1', 9501);

我们打开两个终端,分别启动ServerClient

1
2
3
~/codeDir/phpCode/test # php server.php 
Client:Connect.

1
2
~/codeDir/phpCode/test # php client.php 

讲道理来说,client连接上server之后,是会给server发生字符串'hello world\r\n\r\n'的,但是看样子server好像并没有解析出这个字符串对吧。

问题出在了server端的package_eof的值用的是双引号,而client发送给server的字符串用的是单引号。而PHP在单引号和双引号中解析\r\n\r\n是不一样的(至少在字符串的长度来说都是不同的)。所以我们需要统一一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

$client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

$client->on("connect", function(swoole_client $cli) {
$cli->send("hello world\r\n\r\n");
});

$client->on("receive", function(swoole_client $cli, $data){
echo "Receive: $data";
});

$client->on("error", function(swoole_client $cli){
echo "error\n";
});

$client->on("close", function(swoole_client $cli){
echo "Connection close\n";
});

$client->connect('127.0.0.1', 9501);
1
2
3
4
5
~/codeDir/phpCode/test # php client.php 
Receive: Swoole: hello world

Connection close
~/codeDir/phpCode/test #

此时,server就可以解析出这个\r\n\r\n了。