多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
这里进行数据库的记录操作,很简单。 在Events.php文件里onMessage方法添加几句代码就行 ~~~ public static function onMessage($client_id, $message) { // 向所有人发送 $message_data = json_decode($message,true); if(!$message_data){ return; } switch($message_data['type']){ case "bind": $fromid = $message_data['fromid']; Gateway::bindUid($client_id, $fromid); return; case "say": $text = nl2br(htmlspecialchars($message_data['data'])); $fromid = $message_data['fromid']; $toid = $message_data['toid']; $date=[ 'type'=>'text', 'data'=>$text, 'fromid'=>$fromid, 'toid'=>$toid, 'time'=>time() ]; echo "datasend".$fromid."\n"; echo "datasend".$toid."\n"; //判断用户是否在线,在线给数据库添加1记录值为已读 if(Gateway::isUidOnline($toid)){ //发送消息给接受用户 Gateway::sendToUid($toid,json_encode($date)); $date['isread']= 1; }else{ $date['isread']= 0; } //修改数组type为save,发送到自己的接收信息函数上进行数据保存操作 $date['type'] = "save"; Gateway::sendToUid($fromid,json_encode($date)); return; } } ~~~ 这里是html代码: ``` var fromid = 13; // var toid = 12; var API_URL = "http://localhost/tchat/public/index.php/api/api/"; var ws = new WebSocket("ws://192.168.0.102:8282"); // var ws = new WebSocket("ws://192.168.10.51:8282"); ws.onmessage = function(e){ var message = eval("("+e.data+")"); switch (message.type){ case "init": var bild = '{"type":"bind","fromid":"'+fromid+'"}'; ws.send(bild); return; case "text": console.log(message); if(toid==message.fromid) { $(".chat-content").append(' <div class="chat-text section-left flex"><span class="char-img" style="background-image:"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>' + message.data + '</span> </div>'); } return; case "save": save_message(message); return; } // $(".chat-content").append(' <div class="chat-text section-left flex"><span class="char-img" style="background-image: "></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>' + message.data + '</span> </div>'); // console.log(message); } $(".send-btn").click(function(){ var text = $(".send-input").val(); var message = '{"data":"'+text+'","type":"say","fromid":"'+fromid+'","toid":"'+toid+'"}'; $(".chat-content").append('<div class="chat-text section-right flex"><span class="text"><i class="icon icon-sanjiao3 t-32"></i>'+text+'</span> <span class="char-img" style="background-image: "></span> </div>'); ws.send(message); $(".send-input").val(""); }) function save_message(message){ $.post( API_URL+"insertchat" , message, function(){ },'json' ) } ``` 就添加一个post方法的函数,将数据传回到服务器,由服务器进行数据库记录操作,下面是保存的代码 ~~~ public function insertchat() { if (Request::instance()->isAjax()) { $message = input("post."); $datas['fromid'] = $message['fromid']; $datas['fromname'] = $message['fromid']; $datas['toid'] = $message['toid']; $datas['toname'] = $message['toid']; $datas['content'] = $message['data']; $datas['time'] = $message['time']; $datas['isread'] = $message['isread']; $datas['type'] = 1; Db::name("communication")->insert($datas); } } ~~~