php socket客户端和服务端互相通讯实例
服务端
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2838')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2838><?php
set_time_limit(0);
$host="localhost";
$port=1001;
//创建一个连接
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socketn");
//绑定socket到端口
$result=socket_bind($socket,$host,$port) or die("cannot bind port to socketn");
//开始监听这个端口
$result=socket_listen($socket,4) or die("could not set up socket listenn");
//接受连接,另一个socket来处理通信
$msgsock=socket_accept($socket) or die("cannot accept incoming connectionn");
if($msgsock){
echo date("Y-m-d H:i:s D a");
}
//读取客户端发送过来的信息
$input=socket_read($msgsock,1024) or die("cannot read inputn");
$input=trim($input);
$output=strrev($input)."顺序反过来了吧n";
//对接收到的信息进行处理,然后返回到客户端
socket_write($msgsock,$output,strlen($output)) or die("cannot write");
//关闭socket连接
socket_close($msgsock);
socket_close($socket);
?>
客户端
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4642')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4642><?php
set_time_limit(0);
$host="localhost";
$port=1001;
//创建一个socket
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socketn");
$conn=socket_connect($socket,$host,$port) or die("cannot connect servern");
if($conn){echo "client connect ok!";}
socket_write($socket,"hello world!") or die("cannot write datan");
$buffer=socket_read($socket,1024,PHP_NORMAL_READ);
if($buffer){
echo "response was:".$buffer."n";
}
socket_close($socket);
?>
您可能感兴趣的文章:
PHP 如何进行socket套节字的连接
如何理解php socket
php socket客户端和服务端互相通讯实例
认识HTML5的WebSocket
php为什么不适合socket
php socket讲解与实例
HTML5中WebSocket是什么意思
PHP简单实现客户端和服务端Socket通信
php socket实例之telnet实现的聊天程序
什么是 WebSocket?深入理解html5中WebSocket