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
| <?php
class Server { private $db_conf = [ 'host' => '127.0.0.1', 'port' => '3306', 'name' => 'root', 'pwd' => '123456', 'db' => 'proj' ];
private $secret = '10be8c337984d3a3c470f7cf5239c298';
private $mysql = null, private $serv;
public function __construct() { $this->serv = new swoole_server("0.0.0.0", 9501); $this->serv->set(array( 'worker_num' => 8, 'daemonize' => false, ));
if ($this->serv && !$this->mysql) $this->mysqli_reconnect();
if ($this->mysql && $this->mysql->set_charset('utf8')) { $this->serv->on('Start', array($this, 'onStart')); $this->serv->on('Connect', array($this, 'onConnect')); $this->serv->on('Receive', array($this, 'onReceive')); $this->serv->on('Close', array($this, 'onClose'));
$this->serv->start(); } }
public function mysqli_reconnect() { $this->mysql = new mysqli( $this->db_conf['host'], $this->db_conf['name'], $this->db_conf['pwd'], $this->db_conf['db'], $this->db_conf['port'] );
return $this->mysql; }
public function onStart( $serv ) { }
public function onConnect( $serv, $fd, $from_id) { }
public function onReceive( swoole_server, $serv, $fd, $from_id, $data) {
$response = [ 'nq_id' => 'empty', 'nq_data' => 'empty', 'nq_ref' => 'empty', 'nq_type' => 'empty', ];
if ($data) { $arr = json_decode($data, true);
if ($arr && is_array($arr) && (isset($arr['secret']) && ($arr['secret'] == $this->secret)) && in_array($arr['option'], ['nothing', 'query', 'return']) && isset($arr['uid']) && is_numeric($arr['uid'])) { if ($arr['option'] == 'query') { $sql = 'select * from bm_notice_queues where nq_uid =' .$arr['uid'] .'limit 1';
if ($this->mysql->errno == 2006) { while(!$this->mysqli_reconnect()) { $this->mysqli_reconnect(); } }
$res = $this->mysql->query($sql);
if ($res && is_object($res) && $res->num_rows) { if ($row = $res->fetch_assoc()) { $response['nq_id'] = $row['nq_id']; $response['nq_data'] = $row['nq_data']; $response['nq_ref'] = $row['nq_ref']; $response['nq_type'] = $row['nq_type']; } } } elseif ($arr['option'] == 'return') { if (($arr['status'] == 'success') && is_numeric($arr['return']) && $arr['return'] > 0) { $sql = 'delete from bm_notice_queues where nq_id = '.$arr['return'];
if ($this->mysql->errno == 2006) { while(!$this->mysqli_reconnect()) { $this->mysqli_reconnect(); } }
$this->mysql->query($sql); } } } }
$serv->send($fd, json_encode($response)); }
public function onClose( $serv, $fd, $from_id) { } }
$server = new Server();
|