2個php測試文件
server.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);
?>
client.php
復制代碼 代碼如下:
<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";
$port = 1935;
$ip = "127.0.0.1";
/*
+-------------------------------
* @socket連接整個過程
+-------------------------------
* @socket_create
* @socket_connect
* @socket_write
* @socket_read
* @socket_close
+--------------------------------
*/
$socket = socket_create(AF_INET, SOCK_STREAM, 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, $ip, $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 "發送的內容為:<font color='red'>$in</font> <br>";
}
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 install
php.ini修改配置
增加
復制代碼 代碼如下:
extension=sockets.so
重啟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