前端:websocket脚本
1.实现
<!DOCTYPE html> <meta charset="utf-8" /> <title>WebSocket Test</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script language="javascript" type="text/javascript"> var g_uuid ; var av_img = "http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eorADDRtpTzqxAIZZfVLGP3zpeDepNXq77iazZZT3zAm1icbib0bCvB6SwbBB5ycXcrPhFAN0kZvrGKw/132"; // var wsUri ="ws://echo.websocket.org/"; // var wsUri ="ws://localhost:8765/asdasd?path_name=default_key"; // var wsUri ="ws://192.168.0.196:5211?uuid=" + g_uuid; var output; function init(g_uuid) { var wsUri ="ws://192.168.0.196:5211?uuid=" + g_uuid; document.getElementById('img_2').src = "http://test.account.ndmooc.com/v1/webapp/qrcode/" + g_uuid; output = document.getElementById("output"); testWebSocket(wsUri); } function testWebSocket(wsUri) { 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) { onError(evt) }; } function onOpen(evt) { writeToScreen("连接-onOpen-connected"); //doSend('subscribe|[1.2]'); } function onClose(evt) { writeToScreen("断开连接-onClose-disconnected"); } function onMessage(evt) { writeToScreen('<span style="color: blue;">响应: '+ evt.data+'</span>'); console.log(evt.data); x2 = eval('(' + evt.data + ')'); console.log(x2); if(x2['act'] == 1002){ writeToScreen('<span style="color: blue;">响应: '+ ' 显示切换登录界面(显示用户头像及 切换帐号 按钮)' +'</span>'); document.getElementById('img_2').src = av_img; } //x = $.parseJSON(evt.data); // console.log(x); //websocket.close(); } function onError(evt) { writeToScreen('<span style="color: red;">错误:</span> '+ evt.data); } function doSend(message) { writeToScreen("发送: " + message); websocket.send(message); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } // window.addEventListener("load", init, false); </script> <h2>WebSocket Test1</h2> <div id="output"></div> <img id="img_2" src="http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eorADDRtpTzqxAIZZfVLGP3zpeDepNXq77iazZZT3zAm1icbib0bCvB6SwbBB5ycXcrPhFAN0kZvrGKw/132"> <form id="emit"> <input id="emit_data" type="text" name="emit"> <button type="submit" id="button1"> 提 交 </button> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script> $('form#emit').submit(function(event) { console.log($('#emit_data').val()); var aa = $('#emit_data').val(); doSend(aa); $('#log').append('<p>request: ' + $('#emit_data').val() + '</p>'); return false; }); $(function(){ console.log(11111111111); $.ajax({ type: "GET", url: "http://test.account.ndmooc.com/v1/webapp/generate_uuid?appid=123", data: {}, dataType: "json", success: function(data){ console.log(data); console.log(data['data']['uuid']); g_uuid = data['data']['uuid'] init(g_uuid) } }); }); </script> </html>