php实现tcp连接的原理,PHP实现TCP实例
NotifyService.php
class NotifyService extends Model
{
private static $client;
private static $redis;
/**
* 初始化
*/
protected static function initial()
{
$url = 'tcp://' . config('ctrl_service.host') . ':' . config('ctrl_service.port');
self::$client = @stream_socket_client($url, $errno, $errmsg, 1);
if (!self::$client) {
return false;
}
return true;
}
/**
* redis連接
* 接口并發量較高的時候容易造成TIMEWAIT過多
* 盡量避免多次進行連接
*/
private static function redisConnect()
{
// 判斷是否使用redis 做緩存 如果有連接過
// if (config('cache.type') == 'redis') {
// // redis 連接 判斷是否有已經連接過
// $cache = Cache::init();
// // 獲取緩存對象句柄
// $handler = $cache->handler();
// self::$redis = $handler;
// return;
// }
self::$redis = new Redis();
$host = Env::get('redis.host', '127.0.0.1'); // redis 主機ip
$port = Env::get('redis.port', 6379); // redis 端口
$password = Env::get('redis.password', '123456'); // redis 密碼
$select = Env::get('cache.select', 0); // 數據庫
// 第一個參數為redis服務器的ip,第二個為端口
// self::$redis->connect($host, $port);
self::$redis->pconnect($host, $port);
self::$redis->auth($password); //密碼驗證
self::$redis->select($select); //選擇數據庫
}
/**
* redis斷開
*/
public static function redisClose()
{
self::$redis->close();
}
/**
* app 通知
*/
public static function appNotify($content, $uid = 0)
{
if (!self::initial()) {
return false;
}
$post_data = [
'cmd' => 1010,
'type' => 'notice',
'uid' => (int) $uid,
'msgid' => 88, // 88是于客戶端約定的標識
'content' => json_encode($content),
'loopcount' => 1,
'gid' => 0,
'roomno' => 0,
'interval' => 1,
];
return self::sendMsg($post_data);
}
/**
* 發送消息給控制服轉發到游服
*/
public static function sendMsg($data)
{
// 添加一層外殼轉發
$msg = [
'content' => $data,
'type' => 'forwarding',
];
$msg = json_encode($msg);
$msg .= "n";
return fwrite(self::$client, $msg);
}
/**
* 通知中間件配置相關
*/
public static function middleNoticeConfigInit($data, $redis_subscribe = 'middle_config')
{
self::redisConnect();
$data = json_encode($data);
$res = self::$redis->publish($redis_subscribe, $data);
self::redisClose();
}
}
NotifyService::appNotify([‘type’ => ‘other_close’], $uid);
// 通知中間件重新獲取配置
NotifyService::middleNoticeConfigInit([‘type’ => ‘init_robot_uids’]);
總結
以上是生活随笔為你收集整理的php实现tcp连接的原理,PHP实现TCP实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有关java的名句_关于志气的名言名句(
- 下一篇: 外星人台式机无盘服务器,可以拎走的“台式