php使用长连接
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php使用长连接相关的知识,希望对你有一定的参考价值。
- 安装:
composer require workerman/gateway-worker
- 服务端:
<?php require_once "vendor/autoload.php"; use WorkermanWorker; use GatewayWorkerGateway as gate; use GatewayWorkerBusinessWorker; use GatewayWorkerRegister; use GatewayWorkerLibGateway; use MedooMedoo; $super = array(); $gateway = new gate("websocket://0.0.0.0:2345"); $gateway->count = 4; $gateway->name = ‘gateway‘; $gateway->registerAddress = ‘127.0.0.1:1234‘; $business = new BusinessWorker(); $business->name = ‘business‘; $business->count = 4; $business->registerAddress = ‘127.0.0.1:1234‘; $register = new Register(‘text://0.0.0.0:1234‘); $register->name = ‘register‘; class Events{ public static function onConnect($client_id){ $arr = array( ‘remote_ip‘=>$_SERVER[‘REMOTE_ADDR‘], ‘remote_port‘=>$_SERVER[‘REMOTE_PORT‘], ‘gate_ip‘=>$_SERVER[‘GATEWAY_ADDR‘], ‘gate_port‘=>$_SERVER[‘GATEWAY_PORT‘], ‘client_id‘=>$_SERVER[‘GATEWAY_CLIENT_ID‘] ); $ret = json_encode($arr); return GateWay::sendToCurrentClient($ret); } public static function onMessage($client_id, $message){ return GateWay::sendToCurrentClient($message); } public static function onClose($client_id){ GateWay::sendToAll("client[$client_id] logout "); } } Worker::runAll();
- 客户端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="text"> <br> <input type="button" value="提交"> <script> var ws = new WebSocket(‘ws://192.168.8.81:2345‘) ws.onopen = function(data) { console.log(‘连接开始 ‘) } ws.onmessage = function(data) { console.log(‘接收消息:‘+data.data) } ws.onclose = function(data) { console.log(‘关闭连接 ‘) } ws.onerror = function(data) { console.log(‘遇到错误 ‘) } var text = document.getElementsByTagName(‘input‘)[0] var button = document.getElementsByTagName(‘input‘)[1] button.onclick = function(){ var val = text.value ws.send(val) } </script> </body> </html>
- 测试:
以上是关于php使用长连接的主要内容,如果未能解决你的问题,请参考以下文章