2 Star 5 Fork 6

pdosgk / swoole_framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server_layim.php 8.62 KB
一键复制 编辑 原始数据 按行查看 历史
pdosgk 提交于 2016-12-22 22:49 . swoole框架
<?php
define('DEBUG', 'on');
define("WEBPATH", str_replace("\\","/", __DIR__));
require __DIR__ . '/libs/lib_config.php';
class WebSocket extends Swoole\Protocol\WebSocket
{
protected $message;
static public $table;
public function __construct()
{
parent::__construct();
//创建一个swoole_table。存储客户端信息
$table = new swoole_table(1024);
$table->column('client_id', swoole_table::TYPE_INT);
$table->column('userid', swoole_table::TYPE_INT);
$table->column('username', swoole_table::TYPE_STRING, 20);
$table->create();
self::$table = $table;
}
/**
* @param $serv swoole_server
* @param int $worker_id
*/
function onStart($serv, $worker_id = 0)
{
Swoole::$php->router(array($this, 'router'));
parent::onStart($serv, $worker_id);
}
function router()
{
var_dump($this->message);
}
/**
* 进入
* @param $client_id
*/
function onEnter($client_id)
{
}
/**
* 下线时,通知所有人
*/
function onExit($client_id)
{
//获取客户端用户信息
$userinfo = $this->getClientInfo($client_id);
$message_close = array('type'=>'logout', 'userid'=>$userinfo['userid'], 'from_client_name'=>$userinfo['username'], 'time'=>date('Y-m-d H:i:s'));
self::$table->del($userinfo['userid']);
echo "client {$client_id} closed\n";
$this->broadcast($client_id, json_encode($message_close));
//将下线消息发送给所有人
//$this->log("onOffline: " . $client_id);
//$this->broadcast($client_id, "onOffline: " . $client_id);
}
function getClientInfo($client_id){
foreach (self::$table as $_userid => $_info){
if($_info['client_id'] == $client_id){
$userid = $_userid;
$userinfo = $_info;
break;
}
}
return $userinfo;
}
function onMessage_mvc($client_id, $ws)
{
$this->log("onMessage: ".$client_id.' = '.$ws['message']);
$this->message = $ws['message'];
$response = Swoole::$php->runMVC();
$this->send($client_id, $response);
//$this->broadcast($client_id, $ws['message']);
}
/**
* 接收到消息时
*/
function onMessage($client_id, $ws)
{
// 客户端传递的是json数据
$message_data = json_decode(($ws['message']), true);
if(!$message_data)
{
return ;
}
var_dump($ws['message']);
$this->message = $ws['message'];
switch($message_data['type'])
{
case 'login':
$username = htmlspecialchars($message_data['username']);
$userid = htmlspecialchars($message_data['userid']);
//记录客户端号
self::$table->set($userid, array('client_id' => $client_id, 'username' => $username, 'userid' => $userid));
echo "client {$client_id} open\n";
// 转播给当前房间的所有客户端,xx进入聊天室
$login_message = array('type'=>$message_data['type'], 'client_id' => $client_id, 'username'=>htmlspecialchars($username), 'time'=>date('Y-m-d H:i:s'), 'userid' => $userid);
$this->broadcast($client_id, json_encode($login_message));
// 给当前用户发送用户列表
// 获取所有用户列表 , 除了自己
$clients_list = array();
foreach(self::$table as $key => $row){
if($row['client_id'] != $client_id)
$clients_list[$row['userid']] = $row;
}
$login_message['client_list'] = $clients_list;
$this->send($client_id, json_encode($login_message));
//提取未读消息
/*$model_user_message = model('UserMessage');
$result = $model_user_message->get($userid, 'to_userid');
$message_list = $result->get();
if($message_list){
//返回未读消息
}*/
break;
case 'chatMessage':
if(!$message_data['content']){
return;
}
//保存聊天记录到数据库
$from_user_info = $this->getClientInfo($client_id);
//机器人聊天
if($message_data['to_client_id'] == 1){
$tuling_message = array(
'type'=>'chatMessage',
'from_client_id'=> 1,
'from_client_name' => '晴儿',
'to_client_id'=>$message_data['to_client_id'],
'avatar' => $message_data['avatar'],
'content'=> nl2br(htmlspecialchars($this->getChat($message_data['content']))),
'time'=>date('Y-m-d H:i:s'),
);
$this->send($client_id, json_encode($tuling_message));
return;
}
$to_user_info = self::$table->get($message_data['to_client_id']);
//保存到数据库
$insert_data['userid'] = $from_user_info['userid'];
$insert_data['to_userid'] = $message_data['to_client_id'];
$insert_data['content'] = $message_data['content'];
$model_user_message = model('UserMessage');
$result = $model_user_message->put($insert_data);
var_dump($result);
//如果对方不在线, 则保存到数据库
if(!$to_user_info){
$not_online = array(
'type' => 'not_online',
);
$this->send($client_id, json_encode($not_online));
//
}else{
$new_message = array(
'type'=>'chatMessage',
'from_client_id'=> $from_user_info['userid'],
'from_client_name' =>$message_data['username'],
'to_client_id'=>$message_data['to_client_id'],
'avatar' => $message_data['avatar'],
'content'=> nl2br(htmlspecialchars($message_data['content'])),
'time'=>date('Y-m-d H:i:s'),
);
$this->send($to_user_info['client_id'], json_encode($new_message));
}
break;
case 'addFirend':
//添加好友
//判断是否在线
break;
}
//$this->log("onMessage: ".$client_id.' = '.$ws['message']);
//$this->send($client_id, 'Server: '.$ws['message']);
}
function broadcast($client_id, $msg)
{
foreach ($this->connections as $clid => $info)
{
if ($client_id != $clid)
{
$this->send($clid, $msg);
}
}
}
function saveMessage(){
}
//自动回复
public function getChat($keyword){
//默认使用图灵机器
return $this->getTuling($keyword);
}
//图灵
public function getTuling($keyword){
$url = 'http://www.tuling123.com/openapi/api?key=2e7fd2823e14defb9c903f5ab35e64e4&info='.urlencode($keyword);
$content = $this->_curl($url);
if($content['code'] == 100000){
return $content['text'];
}
return '我现在还小, 等我长大后再回答你的问题';
}
public function _curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$txt = curl_exec($ch);
if (curl_errno($ch)) {
return false;
}
curl_close($ch);
return json_decode($txt, true);
}
}
//require __DIR__'/phar://swoole.phar';
Swoole\Config::$debug = true;
Swoole\Error::$echo_html = false;
$AppSvr = new WebSocket();
$AppSvr->loadSetting(__DIR__."/swoole.ini"); //加载配置文件
$AppSvr->setLogger(new \Swoole\Log\EchoLog(true)); //Logger
/**
* 如果你没有安装swoole扩展,这里还可选择
* BlockTCP 阻塞的TCP,支持windows平台
* SelectTCP 使用select做事件循环,支持windows平台
* EventTCP 使用libevent,需要安装libevent扩展
*/
$enable_ssl = false;
$server = Swoole\Network\Server::autoCreate('0.0.0.0', 9505, $enable_ssl);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array(
'worker_num' => 1,
//'ssl_key_file' => __DIR__.'/ssl/ssl.key',
//'ssl_cert_file' => __DIR__.'/ssl/ssl.crt',
//'max_request' => 1000,
//'ipc_mode' => 2,
//'heartbeat_check_interval' => 40,
//'heartbeat_idle_time' => 60,
));
PHP
1
https://gitee.com/pdosgk/swoole_framework.git
git@gitee.com:pdosgk/swoole_framework.git
pdosgk
swoole_framework
swoole_framework
master

搜索帮助