基于PHP Socket配置以及实例的详细介绍

前端之家收集整理的这篇文章主要介绍了基于PHP Socket配置以及实例的详细介绍前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

2个PHP测试文件
PHP

代码如下:
PHP
//PHPinfo();
//确保在连接客户端时不会超时
set_time_limit(0);
$ip = '127.0.0.1';
$port = 1935;
/*
+-------------------------------
* @socket通信整个过程
+-------------------------------
* @socket_create
* @socket_bind
* @socket_listen
* @socket_accept
* @socket_read
* @socket_write
* @socket_close
+--------------------------------
*/
/*---------------- 以下操作都是手册上的 -------------------*/
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n";
}
if(($ret = socket_bind($sock,$ip,$port)) < 0) {
echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";
}
if(($ret = socket_listen($sock,4)) < 0) {
echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";
}
$count = 0;
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() Failed: reason: " . socket_strerror($msgsock) . "\n";
break;
} else { //发到客户端
$msg ="测试成功!\n";
socket_write($msgsock,$msg,strlen($msg)); echo "测试成功了啊\n";
$buf = socket_read($msgsock,8192);
$talkback = "收到的信息:$buf\n";
echo $talkback; if(++$count >= 5){
break;
};
}
//echo $buf;
socket_close($msgsock);
} while (true);
socket_close($sock);
?>

PHP

代码如下:
PHP
error_reporting(E_ALL);
set_time_limit(0);
echo "

TCP/IP Connection

\n";
$port = 1935;
$ip = "127.0.0.1";
/*
+-------------------------------
* @socket连接整个过程
+-------------------------------
* @socket_create
* @socket_connect
* @socket_write
* @socket_read
* @socket_close
+--------------------------------
*/
$socket = socket_create(AF_INET,SOL_TCP);
if ($socket < 0) {
echo "socket_create() Failed: reason: " . socket_strerror($socket) . "\n";
}else {
echo "OK.\n";
}
echo "试图连接 '$ip' 端口 '$port'...\n";
$result = socket_connect($socket,$port);
if ($result < 0) {
echo "socket_connect() Failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
echo "连接OK\n";
}
$in = "Ho\r\n";
$in .= "first blood\r\n";
$out = '';
if(!socket_write($socket,$in,strlen($in))) {
echo "socket_write() Failed: reason: " . socket_strerror($socket) . "\n";
}else {
echo "发送到服务器信息成功!\n";
echo "发送的内容为:$in
";
}
while($out = socket_read($socket,8192)) {
echo "接收服务器回传信息成功!\n";
echo "接受的内容为:",$out;
}
echo "关闭SOCKET...\n";
socket_close($socket);
echo "关闭OK\n";
?>

侦听

# /usr/local/PHP/bin/PHP /usr/local/apache2/htdocs/server.PHP

请求

# /usr/local/PHP/bin/PHP /usr/local/apache2/htdocs/client.PHP

默认PHP是没有开启Socket的


#cd ./ext/sockets/
# /usr/local/PHP/bin/PHPize
# ./configure --enable-sockets --with-PHP-config=/usr/local/PHP/bin/PHP-config
# make
# make installPHP.ini修改配置
增加

重启apache

# /usr/local/apache2/bin/apachectl restart===================

Windows下的配置

修改PHP.ini
extension=PHP_sockets.dll
重启apache
cmd下起2个
PHP的安装目录C:/PHP/PHP.exe F:web/server.PHP
C:/PHP/PHP.exe F:web/client.PHP 原文链接:https://www.f2er.com/php/26301.html

猜你在找的PHP相关文章