wssocket.php 6.91 KB
Newer Older
Kulya's avatar
Kulya committed
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
<?php
require_once __DIR__ . '/vendor/autoload.php';

/* Laravel connection */

require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$request = Illuminate\Http\Request::capture();

$GLOBALS["wbsock"] = '123';

use Workerman\Worker;

// SSL context.
$context = array(
    'ssl' => array(
        'local_cert'  => '/etc/letsencrypt/live/online.vmajlis.uz/fullchain.pem',
        'local_pk'    => '/etc/letsencrypt/live/online.vmajlis.uz/privkey.pem',
        'verify_peer' => false,
    )
);

// массив для связи соединения пользователя и необходимого нам параметра
$users = [];

// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:8085",$context);

// 4 processes
$ws_worker->count = 4;
$ws_worker->transport = 'ssl';

$getSystemData = function ($req) use($kernel,$request){
	$GLOBALS["datas"] = $req;

	$response = $kernel->handle( $request );
	$res = $response->getContent();
	//$kernel->terminate($request, $response);
	
	return $res;
};

tLog( "-------- ======== WebSOCKET start on [0.0.0.0]:[8085] =========----------" );

$ws_worker->onWorkerStart = function() use (&$users) {

    $inner_tcp_worker = new Worker("tcp://127.0.0.1:12345");

    $inner_tcp_worker->onMessage = function($connection, $data) use (&$users) {
		
		tLog( "onMessage: " . $data );
		
        $data = json_decode($data,true);
		
        // отправляем сообщение пользователю по userId

		if (isset($users[$data["vid"]])) {
			$webconnection = $users[$data["vid"]];
			$webconnection->send('{"ok":"Your msg: '.$data["msg"].'"}');
		}
		
    };
    $inner_tcp_worker->listen();
};


$ws_worker->onConnect = function($connection) use (&$users, $ws_worker) {
	
    $connection->onWebSocketConnect = function($connection) use (&$users, $ws_worker) {
		tLog( "onConnect_GET: " . json_encode($_GET) );
		
        $users[$_GET['v']] = $connection;

		$myConnId =  $connection->id;
		$myConnIP =  $connection->getRemoteIp();
		
		//tLog( "onConnect_LARAV_CONN: " . $vtr );
		
		/*  RESEND to all connections */
		foreach($ws_worker->connections as $allConn){
			tLog( "checkConnSEND: " . $allConn->id );
			if(  $myConnId == $allConn->id ){
				$allConn->send('{"connection":"ok","msg":"Wellcome"}');  //: ['.$_GET['v'].']['.$allConn->id.']['.$myConnId.']
			} /*else {
				if(!empty($vtr)){
					$allConn->send('{"newVisitor":"ok","vid":"'.$_GET['v'].'","cid":"'.$allConn->id.'","visitor":"'.json_encode($vtr).'"}' );
				}
			}*/
		}
		
		
		
		
   };
};



// Emitted when connection Msg
$ws_worker->onMessage = function($connection, $data) use(&$users, $ws_worker,$getSystemData) {
	tLog( "------------=========================--------------------- " );
	
	
	tLog( "onMessage_DATA: " . $data );
	$arData = json_decode($data,true);
	
	tLog( "onMessage_VID: " . $arData["vid"] );
	
	$myConnId =  $connection->id;
	$myConnIP =  $connection->getRemoteIp();	
	
	$arData["cid"] = $myConnId;
	$arData["vip"] = $myConnIP;
	$arData["userkeys"] = array_keys($users);
	
	
	if( !empty( $arData['cmd'] ) ){
		
		$cmdRes = $getSystemData($arData);
		
		tLog( "checkRes_CMD: " . $cmdRes );
		
		$cmdRes = json_decode($cmdRes,true);
		
		tLog( "JSON error------: " . json_last_error() );
		//tLog( "checkRes_VSTRs------: " . $cmdRes["count"] );
		
		
		//array("count"=>count($arVisitors), "allvisitors"=> $arVisitors, "newvisit"=> $newvisit); 
		// NewVisit to All 
		$arLastMessages = ( !empty($cmdRes["arLastMessages"]) ) ? $cmdRes["arLastMessages"] : "";
		$allvstrs = ( !empty($cmdRes["allvisitors"]) ) ? $cmdRes["allvisitors"] : "";
		$allCnt = ( !empty($cmdRes["count"]) ) ? $cmdRes["count"] : 0;
		$toMe = json_encode(array("allvisitors"=>$allvstrs,"lastmessages"=>$arLastMessages,"count"=>$allCnt ));
		
		$connection->send($toMe);
		
		if( !empty($cmdRes["newvisit"]) ) {
			$toAll = json_encode(array("newvisit"=>$cmdRes["newvisit"]));
			
			foreach($users as $uKey => $uConn ){
				if(  $myConnId != $uConn->id ){
					$uConn->send($toAll);
				}
			}
		
		
		}


		return;
	}
	
	if(!empty($arData["message"])){

		$newMsgRes = $getSystemData($arData);
		
		tLog( "checkRes_inc_MSG: " . $newMsgRes );
		
		$arMsgRes = json_decode($newMsgRes,true);
		tLog( "JSON error------: " . json_last_error() );
		
		tLog( "onMessage_Sent_OK: " . $users[$arData['vid']]->id );
		$users[$arData['vid']]->send('{"sent":"ok","oldID":"'.$arData['messageId'].'","newID":"'.$arMsgRes["newMsgId"].'","toName":"'.$arMsgRes["toName"].'","ip":"'.$myConnIP.'","sid":"'.$users[$arData['vid']]->id.'"}');
		
		tLog( "onMessage_Check_Lichka: " . $arData['room'] ."_". $arData['to'] );
		
		if( $arData['room'] != $arData['to'] ){
			$users[$arData['to']]->send('{"newmessage":"ok","msgID":"'.$arMsgRes["newMsgId"].'","msgDate":"'.$arMsgRes["newMsgDate"].'","private":"yes","fromId":"'.$arData['vid'].'","from":"'.$arData['name'].'","message":"'.$arData['message'].'","sid":"'.$users[$arData['to']]->id.'"}');
		} else {
			/*  RESEND to all connections */
			foreach($users as $uKey => $uConn ){
				$cid = $uConn->id;
				if(  $myConnId != $cid ) {
					if( in_array($uKey,$arMsgRes["vkeys"]) ){
						tLog( "checkMsgSEND_to_Other: " . $cid );
						$uConn->send('{"newmessage":"ok","msgID":"'.$arMsgRes["newMsgId"].'","msgDate":"'.$arMsgRes["newMsgDate"].'","fromId":"'.$arData['vid'].'","from":"'.$arData['name'].'","message":"'.$arData['message'].'","sid":"'.$cid.'"}');
					}
				}
			}
		}
		return;
	}
	
	/*
	foreach($ws_worker->connections as $connection){
		tLog( "checkMsgSEND: " . $connection->id );
		if(  $myConnId == $connection->id ){
			$newMsgID = time() . $arData['messageId'];
			$connection->send('{"sent":"ok","oldID":"'.$arData['messageId'].'","newID":"'.$newMsgID.'","ip":"'.$myConnIP.'","sid":"'.$connection->id.'"}'); //Wellcome: [".$_GET['v']."][".$users[$_GET['v']]->id."][".$myConnId."]
		} else {
			$connection->send('{"msgID":"'.$newMsgID.'","fromId":"'.$arData['vid'].'","from":"'.$arData['name'].'","message":"'.$arData['message'].'","sid":"'.$connection->id.'"}'); //NewConnect: [".$_GET['v']."][".$users[$_GET['v']]->id."][".$myConnId."]
		}
	}
	*/
	/*
    if( isset($users[$arData['vid']]) ) {
		$connection->send("I know you! [".$users[$arData['vid']]->id."]");
	} else {
		$connection->send("Who you! [".$connection->id."]");
	}*/
		
};

// Emitted when connection closed
$ws_worker->onClose = function($connection) use(&$users) {
	tLog( "onClose: " . $connection->id );
    // удаляем параметр при отключении пользователя
    //$user = array_search($connection, $users);
    $vid = array_search($connection, $users);
    unset($users[$vid]);
	foreach($users as $uConn ){
		$uConn->send('{"closevisitor":"'.$vid.'"}');
	}
};

function tLog( $text ) {
	$logfile = __DIR__."/websocket.log";
	$nowdate = date("Y-m-d_H:i:s");
	file_put_contents($logfile, $nowdate."[".$text."] \n", FILE_APPEND | LOCK_EX);
}

// Run worker
Worker::runAll();