cocos2d-js 中增加websocket連線c++伺服器
伺服器原始碼用: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();