能同经闻

主页 > 聚焦 >

workerman实现tcp和http双向连接的方法介绍

  下面给大家介绍一下workerman实现tcp和http双向连接的方法介绍。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

  相关:《workerman教程》

  workerman实现tcp和http双向连接

  本来想采用GatewayWorker来完成的,最后还是想写简单一点。用workerman进行和智能设备的tcp长连接和http的短连接。
场景需求。小程序端传给服务器开启设备或调节温度等操作。服务器和小程序http短连接,拿到信息后与设备进行tcp长连接。

  1、建立tcp连接

  protected $socket = 'tcp://0.0.0.0:2346'; protected $processes = 1; protected $uidConnections = array();

  2、在onWorkerStart建立http连接

  global $ws_worker; // 监听5678端口,协议websocket/http $ws_worker = new Work('网页ws发来数据的时候的处理,可根据需要做处理,这里省略 $ws_worker->onMessage = function($ws_connection, $data){ $redis = new Redis(); //获取http发过来的http值 $data = $data['get']; if(empty($data['type'])){ $ws_connection->send("type为空"); }elseif($data['type'] == 1){ //开机 //拿mac去redis验证是否存在,然后拿拿到http进行访问请求开机。做个定时器。到期自动请求设备关机 $mac = $redis->hGet('facility',$data['mac']); if(!$mac){ $ws_connection->send("mac地址错误"); } $status = $this->sendMessageByUid($mac,'开机');//像指定用户发送消息 if($status == 1){//回调码,判断是否成功 $ws_connection->send("开机成功"); }else{ $ws_connection->send("发生错误"); } }elseif($data['type'] == 2){ //关机 //拿mac去redis验证是否存在,然后拿拿到http进行访问请求关机。 $mac = $redis->hGet('facility',$data['mac']); if(!$mac){ $ws_connection->send("mac地址错误"); } $status = $this->sendMessageByUid($mac,'关机');//像指定用户发送消息 if($status == 1){//回调码,判断是否成功 $ws_connection->send("关机成功"); }else{ $ws_connection->send("发生错误"); } } }; $ws_worker->listen(); }

  上面代码为demo案例。下面做点连接的测试,业务代码自行参考

  3、tcp连接与http连接

   /** * 当连接建立时触发的回调函数 * @param $connection */ public function onConnect($connection) { $connection->send(“tcp连接\n"); echo 'tcp连接'; }

  我们做一个客户端的tcp连接请求。

  <?php set_time_limit(0); $host = "xxxxxxxx";//这里是你的服务器ip $port = 2346;//这里是你的服务器端口 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket\n"); $connection = socket_connect($socket, $host, $port) or die("Could not connet server\n"); $mac = array("mac"=>'123456','ip'=>'1.2.3.4'); socket_write($socket, json_encode($mac)) or die("Write failed\n"); while ($buff = socket_read($socket, 1024, PHP_NORMAL_READ)) { echo '1'; echo("Response was:" . $buff . "\n"); echo("input what you want to say to the server:\n"); $text = fgets(STDIN); socket_write($socket, $text); } socket_close($socket);

  我们在终端运行这个php文件和server文件,当建立了连接时。服务端会输出tcp连接(此时已是长连接)

  注:当用tcp连接发送消息的时候,注意粘包问题。每个消息后加"\n"代表换行

  
我们在试一下http连接,http连接就简单多了。url访问就可以了

  global $ws_worker; $ws_worker = new Work('连接"; }

  
这个简单的例子应该都懂。接下来就差业务代码了,就看自己发挥了。

  编程教学!!