php利用stream_socket_server与stream_socket_client
发布:smiling 来源: PHP粉丝网 添加日期:2014-08-06 14:47:27 浏览: 评论:0
- //以上php为服务端,它将监听消息,直到按下:ctrl+c
- while(true)
- {
- //每5秒执行一次
- receive_message('127.0.0.1','85',5);
- }
- //自定义函数用于获取消息
- function receive_message($ips教程erver,$portnumber,$nbsecondsidle)
- {
- //创建socket
- $socket=stream_socket_server('tcp://'.$ipserver.':'.$portnumber, $errno, $errstr);
- if(!$socket)
- {
- //如果创建socket失败输出内容
- echo "$errstr ($errno)<br />n";
- }
- else
- {
- //如果创建成功则接受socket连接并获取信息
- while($conn=@stream_socket_accept($socket,$nbsecondsidle))
- {
- $message=read($conn,1024);
- echo 'i have received that : '.$message;
- fputs ($conn, "okn");
- fclose ($conn);
- }
- fclose($socket);
- }
- }
- //server结束
- ?>
- <?php
- //以下代码为客户端,它将发送信息并读取回复
- send_message('127.0.0.1','85','message to send...');
- //自定义函数,发送信息
- function send_message($ipserver,$portserver,$message)
- {
- $fp=stream_socket_client("tcp://$ipserver:$portserver", $errno, $errstr);
- if(!$fp)
- {
- echo "erreur : $errno - $errstr<br />n";
- }
- else
- {
- fwrite($fp,"$messagen");
- $response = fread($fp, 4);
- if($response != "okn")
- {
- echo 'the command couldn't be executed...ncause :'.$response;
- }
- else
- {
- echo 'execution successfull...';
- }
- fclose($fp);
- }
- }
Tags: stream_socket_server
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)