插座(fsockopen)如何在php中使用

插座(fsockopen)如何在php中使用?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

, fsockopen函数能够运用,首先要开启php . ini中的allow_url_open=,
fsockopen是对套接字客户端代码的封装,该函数中封装了socket_create, socket_connect。
<强>服务器端代码:服务器。php

代码如下:


& lt; ? php
error_reporting (E_ALL);
set_time_limit (0);
$地址=& # 39;127.0.0.1 # 39;;
端口=10008美元;
//创建端口
如果(($袜子=socket_create (AF_INET, SOCK_STREAM SOL_TCP))===false) {
回声“socket_create()失败,原因是:“。socket_strerror (socket_last_error ())。“\ n"
}
//绑定
如果(socket_bind(袜子、地址、端口美元)===false) {
回声“socket_bind()失败,原因是:“。socket_strerror (socket_last_error(袜子)美元)。“\ n"
}
//监听
如果(socket_listen(袜子美元,5)===false) {
回声“socket_bind()失败,原因是:“。socket_strerror (socket_last_error(袜子)美元)。“\ n"
}
,(真正的){
//得到一个链接
如果(($ msgsock=socket_accept(袜子)美元)===false) {
回声“socket_accepty()失败,原因是:“.socket_strerror (socket_last_error(袜子)美元)。“\ n"
打破;
}
//欢迎发送到客户端
$味精=?。你们;字体颜色=& # 39;红色# 39;在服务器发送:welcome & lt; br/祝辞;“
socket_write (msgsock,味精、美元strlen (msg)美元);//返回信息给客户端
回声& # 39;阅读客户端消息\ n # 39;;
$ buf=socket_read (msgsock 8192美元);//获取客户端发送过来的信息
$反??。收到的消息:buf \ n"美元;;
echo $反馈;
如果(错误===socket_write (msgsock,反馈,美元strlen(反馈美元))){//返回信息给客户端
回声“socket_write()失败的原因:“。socket_strerror (socket_last_error(袜子)美元)干净\ n";其他
} {
回声& # 39;发送成功# 39;;
}
socket_close ($ msgsock);
}
socket_close($袜子);


客户端代码:fsocket。php

代码如下:


& lt; ?php
$ fp=fsockopen (“127.0.0.1" 10008, $ errno, errstr美元,10);
如果(! $ fp) {
回声errstr美元。“;(“。errno美元。“)& lt; br> n";其他
} {
在美元=巴?http/1.1 \ r \ n";
$。=爸鞒秩?localhost \ r \ n";
$。=傲?紧密\ r \ n \ r \ n";
fputs (fp,在美元);
, (! feof (fp)美元){
回声fgets (fp 128美元);
}
文件关闭(fp);
}

关于套接字(fsockopen)如何在php中使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。

插座(fsockopen)如何在php中使用