PHP基于socket實(shí)現(xiàn)的簡單客戶端和服務(wù)端通訊功能示例
本文實(shí)例講述了PHP基于socket實(shí)現(xiàn)的簡單客戶端和服務(wù)端通訊功能。分享給大家供大家參考,具體如下:
服務(wù)器端:
<?php
set_time_limit(0);
$host="localhost";
$port=1001;
//創(chuàng)建一個連接
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
//綁定socket到端口
$result=socket_bind($socket,$host,$port) or die("cannot bind port to socket\n");
//開始監(jiān)聽這個端口
$result=socket_listen($socket,4) or die("could not set up socket listen\n");
//接受連接,另一個socket來處理通信
$msgsock=socket_accept($socket) or die("cannot accept incoming connection\n");
if($msgsock){
echo date("Y-m-d H:i:s D a");
}
//讀取客戶端發(fā)送過來的信息
$input=socket_read($msgsock,1024) or die("cannot read input\n");
$input=trim($input);
$output=strrev($input)."順序反過來了吧\n";
//對接收到的信息進(jìn)行處理,然后返回到客戶端
socket_write($msgsock,$output,strlen($output)) or die("cannot write");
//關(guān)閉socket連接
socket_close($msgsock);
socket_close($socket);
?>
客戶端:
<?php
set_time_limit(0);
$host="localhost";
$port=1001;
//創(chuàng)建一個socket
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
$conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");
if($conn){echo "client connect ok!";}
socket_write($socket,"hello world!") or die("cannot write data\n");
$buffer=socket_read($socket,1024,PHP_NORMAL_READ);
if($buffer){
echo "response was:".$buffer."\n";
}
socket_close($socket);
?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php socket用法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP fgetcsv 定義和用法(附windows與linux下兼容問題)
PHP fgetcsv() 函數(shù)從文件指針中讀入一行并解析 CSV 字段。與PHP fgets() 類似,不同的是 PHP fgetcsv() 解析讀入的行并找出 CSV 格式的字段,然后返回一個包含這些字段的數(shù)組2012-05-05
PHP基于數(shù)組實(shí)現(xiàn)的堆棧和隊列功能示例
這篇文章主要介紹了PHP基于數(shù)組實(shí)現(xiàn)的堆棧和隊列功能,結(jié)合實(shí)例形式分析了php基于數(shù)組的array_push()、array_pop()、array_shift()等函數(shù)實(shí)現(xiàn)堆棧與隊列的入棧、出棧以及隊列的添加、刪除等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
PHP 中的面向?qū)ο缶幊蹋和ㄏ虼笮?PHP 工程的辦法
PHP 中的面向?qū)ο缶幊蹋和ㄏ虼笮?PHP 工程的辦法...2006-12-12
PHP實(shí)現(xiàn)多維數(shù)組多字段自定義排序
這篇文章主要介紹了PHP實(shí)現(xiàn)多維數(shù)組多字段自定義排序,通過將待排序數(shù)組的各個數(shù)組的$field保存在一維數(shù)組fieldArr中,在傳入array_multisort中參與排序,相當(dāng)于對$field一維數(shù)組的排序,而后根據(jù)排序后的key重新構(gòu)建傳入的待排序數(shù)組,需要的朋友可以參考下2023-10-10

