今天是:2025年4月7日 星期一
记住用户名密码
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <?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(); |
1 2 3 4 5 6 7 8 9 10 11 12 | 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 条