记住用户名密码
php
<?php use Workerman\Worker; use Workerman\Connection\TcpConnection; require_once __DIR__ . '/vendor/autoload.php'; /* ws = new WebSocket("wss://xxx:1234/wss"); ws = new WebSocket("wss://xxx:12306/wss"); ws.onopen = function() { alert("连接成功"); ws.send('tom'); alert("给服务端发送一个字符串:tom"); }; ws.onmessage = function(e) { alert("收到服务端的消息:" + e.data); }; */ $global_uid = 0; // 这里设置的是websocket协议(端口任意,但是需要保证没被其它程序占用) $worker = new Worker('websocket://0.0.0.0:12306'); // 设置transport开启ssl,websocket+ssl即wss $worker->transport = 'tcp'; // ====这里进程数必须必须必须设置为1==== $worker->count = 1; // 新增加一个属性,用来保存uid到connection的映射(uid是用户id或者客户端唯一标识) $worker->uidConnections = array(); $worker->onMessage = function(\Workerman\Connection\TcpConnection $connection, $data) { $data=json_decode($data,1); global $worker; if($data['type']==1){//绑定uid $connection->uid=$data['user_id']; $worker->uidConnections[$connection->uid] = $connection; } elseif($data['type']==2){//分配客户(第一次分配) sendMessageByUid($data['user_id'], json_encode(['type'=>1])); } }; // 当有客户端连接断开时 $worker->onClose = function(TcpConnection $connection) { global $worker; if(isset($connection->uid)) { // 连接断开时删除映射 unset($worker->uidConnections[$connection->uid]); } }; // 向所有验证的用户推送数据 function broadcast($message) { global $worker; foreach($worker->uidConnections as $connection) { $connection->send($message); } } // 针对uid推送数据 function sendMessageByUid($uid, $message) { global $worker; if(isset($worker->uidConnections[$uid])) { $connection = $worker->uidConnections[$uid]; $connection->send($message); } } \Workerman\Worker::runAll();
location /wss { proxy_pass http://127.0.0.1:12306; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_connect_timeout 30s; proxy_read_timeout 86400s; proxy_send_timeout 30s; }
目前有 0 条留言 其中:访客:0 条, 博主:0 条