服务器源码用:http://blog.csdn.net/chuanyu/article/details/45918965
cocos2d-js框架 MyJSGame,其它的都是默认生成的,自己添加了 test_connnect.js
首先在project.json 增加 src/test_connect.js
然后在 app.js中增加 test(); 调用自己添加的函数
在test_connect.js 最后先 调用 connect(),连接服务器
下面放上 整个 test_connect.js源码:
/* test_connect.js */ function OutputLog(msg){ var content = '<p>' + msg + '</p>'; alert(content); //$('#consoleBox').append(content); }; function test(){ //alert("It's a test !"); var jsonStr = "{\"total\":100,\"data\":[{\"id\":10001,\"name\":\"scott\"},{\"id\":10002,\"name\":\"tiger\"}]}"; //var jsonObj = window.JSON.parse(jsonStr); socket.send('5'+jsonStr); }; function testView(msg){//解析网络字符串 //alert("It's a testView !"); var jsonObj = window.JSON.parse(msg); var str = "---json网络字符串解析结果:---<br>"; str += "<span>Total:"+jsonObj.total+ "</span><br><span>Data:</span><br><span>"; for(var i=0;i<jsonObj.data.length; i++) str += "id:"+jsonObj.data[i].id +",name:"+jsonObj.data[i].name+"<br>"; str += "</span><br>"; OutputLog(str); }; function connect(){ cc.log("connect is in"); var host = "ws://localhost:81/test"; //host address //var host = "ws://"+$('#pseudo').val()+":81/cy"; try{ socket = new WebSocket(host); //new a websocket OutputLog('Socket Status: '+socket.readyState); socket.onopen = function(){ //open socket OutputLog('Socket Status: '+socket.readyState+' (open)'); var pseudoName = "chuanyu"; socket.send('0'+pseudoName); //send a init msg } socket.onmessage = function(msg){//listen var str = ""; str = msg.data; var id = str.substr(0,1); var separator = str.indexOf("|"); var arg1 = ""; var arg2 = ""; if(separator != -1) { arg1 = str.substr(1,separator-1); arg2 = str.substr(separator+1); } else arg1 = str.substr(1); if(id == "0"){ OutputLog('Server reply : '+arg1); } if(id == "1"){ OutputLog('Server echo msg : '+arg1); } if(id == "2"){ OutputLog(arg1 + ' said : ' + arg2); } if(id == "3"){ OutputLog(arg1 + ' broadcasted : ' + arg2); } if(id == "4"){ OutputLog('Server streamed : '+arg1); } if(id == "5"){ OutputLog('Server test msg : '+arg1); testView(arg1); } } socket.onclose = function(){ OutputLog('Socket Status: '+socket.readyState+' (Closed)'); } } catch(exception){ OutputLog('Error'+exception); } } connect();
原文链接:/cocos2dx/342858.html