thinkphp socket类的简单使用
服务端
//报错级别
error_reporting(E_ALL);
//设置长链接
set_time_limit(0);
//ip
$address = "127.0.0.1";
//端口
$port = 10005;
//创建一个套接字
if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) ===false){
echo "创建一个套接字 失败" . "\n";
}
//启动套接字
if(socket_bind($sock, $address,$port)===false){
echo "启动套接字 失败" . socket_strerror(socket_last_error($sock)) . "\n";
}
//监听端口
if(socket_listen($sock,5) === false){
echo "监听端口 失败" . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
//似乎是接收客户端传来的消息
if(($msgsock=socket_accept($sock))===false){
echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";
break;
}
//echo "读取客户端传来的消息"."\n";
$buf = socket_read($msgsock, 8192);
$talkback = "我已经成功接到客户端的信息了。现在我还回信息给客户端"."\n";
if(false=== socket_write($msgsock, $talkback)){
echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n";
}else{
echo "return info msg ku fu duan success"."\n";
}
socket_close($msgsock);
}while (true);
socket_close($sock);
?>
客户端
引入Tp的socket类
require("./Socket.class.php");
$confing = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 10005,
'timeout' => 1800
);
$Socket = new Socket($confing);
if($Socket->connect()){
echo "TP类 创建Socket链接成功!
socket.zip ( 3.06 KB 下载:473 次 )
AD:真正免费,域名+虚机+企业邮箱=0元