socket
最后更新于:2022-04-02 02:32:08
[TOC]
## 函数
```
stream_socket_accept
stream_socket_client
stream_socket_enable_crypto
stream_socket_get_name 获取本地或者远程的套接字名称
stream_socket_pair
stream_socket_recvfrom
stream_socket_sendto
stream_socket_server
stream_socket_shutdown
stream_set_blocking 为资源流设置阻塞或者阻塞模式
stream_set_timeout 设置超时时间
```
## 实例
## 创建socket 服务
```
$socket = stream_socket_server("0.0.0.0:9090",$errno,$errstr);
if (!$socket){
echo "$errstr ($errno)
\n"; die(); } while($client = stream_socket_accept($socket,60)){ print_r(stream_socket_get_name($client,true)); // 也可使用 fread 与fwrtie while ($msg = @stream_socket_recvfrom($client,1024)){ print_r($msg."\n"); stream_socket_sendto($client,"to:".$msg); fclose($client); } } ``` ### 模拟socket客户端 ``` $fp = stream_socket_client("tcp://localhost:8010", $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)
\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\nHost: localhost\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp); } ```
';
\n"; die(); } while($client = stream_socket_accept($socket,60)){ print_r(stream_socket_get_name($client,true)); // 也可使用 fread 与fwrtie while ($msg = @stream_socket_recvfrom($client,1024)){ print_r($msg."\n"); stream_socket_sendto($client,"to:".$msg); fclose($client); } } ``` ### 模拟socket客户端 ``` $fp = stream_socket_client("tcp://localhost:8010", $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)
\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\nHost: localhost\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp); } ```