Skip to content

Commit

Permalink
Update Socket API doc
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Feb 19, 2024
1 parent 07a3e60 commit 5e69b52
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/cn/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ PHP 扩展
* [内存拷贝](php/memory.md)
* [性能测试](benchmark.md)
* [IDE 提示](php/composer.md)
* [Socket API](php/socket.md)

Python 模块
---
Expand Down
3 changes: 2 additions & 1 deletion docs/cn/php/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ $class = $m->$className;
- `PyCore::dict()` 构造一个字典对象
- `PyCore::set()` 构造一个集合对象
- `PyCore::range()` 构造一个范围序列
- `PyCore::scalar()``PyObject` 对象转为 `PHP` 的标量类型,例如 `PyStr` 将转为 `PHP 字符串``Dict/Tuple/Set/List` 将转为 `Array`
- `PyCore::scalar($pyobj)``PyObject` 对象转为 `PHP` 的标量类型,例如 `PyStr` 将转为 `PHP 字符串``Dict/Tuple/Set/List` 将转为 `Array`
- `PyCore::fileno($fp)` 获取 `PHP Stream` 资源的文件描述符,请注意仅支持 `tcp/udp/unix` 类型的资源

> `PyCore` 实现了 `__callStatic()` 魔术方法,对于 `PyCore` 静态方法调用会自动调用 `Python``builtins` 模块对应的方法 ,
> 可参考 [Built-in Functions](https://docs.python.org/3/library/functions.html) 了解更多内置方法的使用
Expand Down
49 changes: 49 additions & 0 deletions docs/cn/php/socket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Socket API
=====
`phpy` 编程开发中经常需要使用 `Socket API` 编写网络通信程序,
可使用下面的方法实现 `Python Socket 对象``PHP Stream 资源` 互相转换。

Python 转 PHP
-----
```php
$socket = PyCore::import('socket');
const HOST = "127.0.0.1";
const PORT = 5432;

$client = $socket->socket($socket->AF_INET, $socket->SOCK_STREAM);
$client->connect(PyCore::tuple([HOST, PORT]));

$fp = fopen('php://fd/' . $client->fileno(), 'rw');
fwrite($fp, $msg);
$data = fread($fp, 1024);
fclose($fp);
```

- 使用 `Python Socket.fileno()` 方法获取文件描述符
- 使用 `PHP fopen('php://fd/{$fileno}')` 将文件句柄对应的 `Socket` 转为 `PHP Stream`
- 使用 `fwrite/fread/fclose` 读写、关闭句柄

`fopen()` 会复制文件描述符,因此 `fclose()` 关闭时不会影响 `Python Socket 对象`
依然可以使用 `Python Socket API` 对此网络连接进行数据传输操作。

PHP 转 Python
----
```php
$socket = PyCore::import('socket');

$HOST = "127.0.0.1";
$PORT = 5432;

$fp = stream_socket_client("tcp://$HOST:$PORT", $errno, $errstr, 30);
if (!$fp) {
exit("Error: $errstr ($errno)\n");
}
$client = $socket->fromfd(PyCore::fileno($fp), $socket->AF_INET, $socket->SOCK_STREAM);
fclose($fp);
```

- 使用 `PyCore::fileno($fp)` 方法获取 `PHP Stream` 文件描述符
- 使用 `Python Socket.fromfd()` 将文件句柄对应的 `Socket` 转为 `Python Socket 对象`

`Socket.fromfd()` 会复制文件描述符,因此 `Python Socket` 关闭时不会影响 `PHP Stream`
依然可以使用 `PHP``fwrite/fread/fclose` 对此网络连接进行数据传输操作。
4 changes: 0 additions & 4 deletions examples/socket/test.php

This file was deleted.

0 comments on commit 5e69b52

Please sign in to comment.