首页 > 代码库 > WebSocket实战之——携带Token验证绑定clientId到uid(微信)
WebSocket实战之——携带Token验证绑定clientId到uid(微信)
HTML代码:通过为、
<!DOCTYPE> <html> <meta charset="utf-8"/> <title>WebSocket Test</title> <script src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> var wsUri = "ws://120.26.220.223:8283"; var output; var clientId; function init() { output = document.getElementById("output"); testWebSocket(); websocket.send("hello \n"); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function (evt) { onOpen(evt) }; websocket.onclose = function (evt) { onClose(evt) }; websocket.onmessage = function (evt) { onMessage(evt) }; websocket.onerror = function (evt) { one rror(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen(‘<span style="color: blue;">RESPONSE: ‘ + evt.data + ‘</span>‘); } function one rror(evt) { writeToScreen(‘<span style="color: red;">ERROR:</span> ‘ + evt.data); } function forExample() { var myJsonStr = setJson(myJsonStr, "clientId", clientId); myJsonStr = setJson(myJsonStr, "type", "say"); myJsonStr = setJson(myJsonStr, "userId", "565081"); myJsonStr = setJson(myJsonStr, "userName", "龙隆蟀舞"); myJsonStr = setJson(myJsonStr, "userImage", "http:\/\/wx.qlogo.cn\/mmopen\/eMWJkc6M6KoWxQqLKuGfPjxRPGO3SmMjeY0I0jJ6WTdGwaEuBm6Z42SsHtVG3afwD71HLb0ZBV8DepIYGVDdVVscQdyQ4siax\/0"); myJsonStr = setJson(myJsonStr, "roomId", "005"); myJsonStr = setJson(myJsonStr, "message", "哇哈哈哈哈"); myJsonStr = setJson(myJsonStr, "time", "1470300123908"); writeToScreen("EXAMPLE: " + myJsonStr); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } //添加或者修改json数据 function setJson(jsonStr, name, value) { if (!jsonStr)jsonStr = "{}"; var jsonObj = JSON.parse(jsonStr); jsonObj[name] = value; return JSON.stringify(jsonObj) } function toJson(str) { var json = eval(‘(‘ + str + ‘)‘); return json; } function sub(){ var $userId = 123456; websocket.send("{‘user_id‘:"+$userId+"}"+"\n"); } window.addEventListener("load", init, false); </script> <h2>WebSocketDemo</h2> token:<input type="text" name="token" id="token"><p></p> 数据:<input type="text" style="height: 50px; width: 100%;" name="data" id="data"><p></p> <button id="submit" onclick="sub()" >提交</button> <p></p> <button id="submit" onclick="forExample()" >JSON数据</button> <p></p> <div id="output"></div> </html>
通过JS的websocket直接向消息服务器发送消息:
//自动检查当前页面时候可以观看 function authCheck($parm,$flag,$isRepeal) { if($isRepeal == false){ closeVideo(); return false; } var returnCode; // 存放同步过来的数据 var $openId = "{{openId}}"; var $liveId = "{{live.id}}"; console.warn($openId); var url = "/redis/authcheck"; var data =http://www.mamicode.com/ { ‘openId‘: $openId, ‘liveId‘:$liveId }; var $userId; $.ajax({ ‘type‘: ‘POST‘, ‘url‘: url, ‘data‘: data, ‘dataType‘: ‘json‘, async: false, //true 异步,false 同步 success: function (response) { console.warn(‘这是第一次执行‘ + response); if (response.errcode == 200) { returnCode = response.errcode; if ($flag == false) { //initPost($parm, $userId); var data =http://www.mamicode.com/ { user_id:response.user_id, openId:response.openId, sign:response.sign }; websocket.send(JSON.stringify(data));//这里携带的参数将会在消息服务器端接受【】 } console.log(‘恭喜你第一次执行时可以看直播视频了‘); $(".channel").each(function () { var ch = $(this); var id = ch.attr("id"); var ad = ch.data("ad"); var HLS = "http://{{live.server|default(‘cdn1.amailive.com‘)}}/hls/" + id + ".m3u8"; ch.data("src", ""); var state = ch.data("state"); if (state != 3) { if (ad != null && ad != "") { ch.data("src", ad); } return; } $.get(HLS, function () { ch.data("src", HLS); }).fail(function () { if (ad != null && ad != "") { ch.data("src", ad); } }); }); } else if (response.errcode == 500) { // alert(‘500:‘+$userId); $(".channel").each(function () { var ch = $(this); ch.data("src", ""); }); closeVideo(); // console.log(‘你没有权限观看这个视频页面1111‘); } else { $(".channel").each(function () { var ch = $(this); ch.data("src", ""); }); console.log(‘未知的错误‘); } } }); } // setInterval(‘authCheck()‘,10000);
【1】通过WEB服务端代码:绑定clientId和Uid
//将 client_id 与 uid 绑定 public function bindUserAction() { header("Access-Control-Allow-Origin:*"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); Gateway::$registerAddress = ‘120.26.220.223:1238‘; $userId = $this->request->getPost(‘userId‘); $clientData = json_decode($this->request->getPost(‘clientData‘), true); $clientId = Gateway::bindUid($clientData[‘clientId‘], $userId); if($clientId == true){ $result = array("errcode" => 200, "errmsg" => "bind userId success", "status" => "{$clientId}"); return $this->toJson($result); } $result = array("errcode" => 500, "errmsg" => "bind userId fail", "status" => "{$clientId}"); return $this->toJson($result); }
【2】通过消息服务端代码:绑定clientId 和Uid(携带参数验证的)
/** * 主逻辑 * 主要是处理 onConnect onMessage onClose 三个方法 * onConnect 和 onClose 如果不需要可以不用实现并删除 */ class Events { /** * 当客户端连接时触发 * 如果业务不需此回调可以删除onConnect * * @param int $client_id 连接id */ public static function onConnect($client_id) { // 向当前client_id发送数据 $arr = array(‘status‘ => ‘Connection Success‘, ‘clientId‘ => $client_id); Gateway::sendToClient($client_id, json_encode($arr)); } /** * 当客户端发来消息时触发 * @param int $client_id 连接id * @param mixed $message 具体消息 */ public static function onMessage($client_id, $message) { $msgDate = json_decode($message, true); // 检测签名 if (!isset($msgDate[‘sign‘])) { Gateway::sendToAll("$client_id:Signature cannot be empty"); return false; } //获取本地token签名 $signToken = self::checkSign($msgDate[‘user_id‘], $msgDate[‘openId‘]); //token签名验证通过则绑定uid if ($signToken != $msgDate[‘sign‘]) { Gateway::sendToAll("$client_id:Signature verification failed or expired"); return false; } GateWay::bindUid($client_id, $msgDate[‘user_id‘]); Gateway::sendToAll("$client_id:$message"); } /** * 当用户断开连接时触发 * @param int $client_id 连接id */ public static function onClose($client_id) { // 向所有人发送 //GateWay::sendToAll("$client_id logout"); } // 服务端签名 public static function checkSign($uid, $openId) { $key = ‘http://ford4s.amailive.com/‘; $sign = md5($key . $uid . $openId); return $sign; } }
WebSocket实战之——携带Token验证绑定clientId到uid(微信)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。