用php TCP 实现简单的消息推送
需要安装 swoole扩展
参考文档:http://www.swoole.com/
server.php
//tcp server file
//please see http://www.swoole.com/
require __DIR__.'/config.php';
require __DIR__.'/function.php';
$serv = new swoole_server("192.168.100.200", 9501);
$redis = new redis();
$redis->pconnect($redis_host ,$redis_port );
$redis->select($redis_db);
$serv->set(array(
'worker_num' => 8, //工作进程数量 , 这个一般是cpu的2倍
//'daemonize' => true, //是否作为守护进程
));
$serv->on('connect', function ($serv, $fd) {
echo "Client-----{$fd} ----- Connect.\n";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) use ($redis) {
$jsonData = json_decode($data, true ) ;
$userid = (isset($jsonData['userid'])) ? $jsonData['userid'] : 0 ;
if(!$userid){
$serv->send($fd, json_encode(array('code' => -1 , 'message' => 'params error' )));
}else{
$redis_data = $redis->rpop('message_'.$userid );
if(!$redis_data || $redis_data == '' ){
$serv->send($fd, json_encode(array('code' => 0 , 'message' => '没有新的消息' )));
}else{
//把消息插入到已读的列表中
$redis_data = json_decode($redis_data , true );
$redis_data['read_time'] = date("Y-m-d H:i:s" , time());
$read_data = json_str($redis_data);
$redis->zIncrBy("read_".$userid ,1 ,$read_data);
$serv->send($fd, $read_data);
}
}
//$serv->close($fd);
});
$serv->on('close', function ($serv, $fd) {
$serv->close($fd);
echo "Client: ----{$fd} -- Close.\n";
});
$serv->start();
function.php
/**************************************************************
*
* 使用特定function对数组中所有元素做处理
* @param string &$array 要处理的字符串
* @param string $function 要执行的函数
* @return boolean $apply_to_keys_also 是否也应用到key上
* @access public
*
*************************************************************/
if(!function_exists("arrayRecursive")){
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000) {
die('possible deep recursion attack');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}
}
/**************************************************************
*
* 将数组转换为JSON字符串(兼容中文)
* @param array $array 要转换的数组
* @return string 转换得到的json字符串
* @access public
*
*************************************************************/
if(!function_exists("json_str")){
function json_str($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
}
config.php
//redis config
$redis_host = "192.168.100.200" ;
$redis_port = "6379";
$redis_db = 1;
运行:
/usr/local/php/bin/php server.php