Websocket on cocos creator client side

hi,
can anyone tell me if cocos creator includes a client api for websockets as suggested on their website? if not what is a good api to include and how will it be put in the assets folder, how will it be imported and how are the async functions called for networking purposes?
Thank you!

Recently i suggested to @slackmoehrle to add documentation about WebSockets. Hope it helps (in the future, haha).

Yes @tranthor suggested Web Sockets documentation. There is some documentation here: https://docs.cocos2d-x.org/creator/manual/en/scripting/network.html?h=websock

1 Like

hi @slackmoehrle ,
I would like to know if I need to import any files into my typescript script in order to use websockets.
I also don’t know how to call async functions from the typescript script.
any help on these two topics would be greatly appreciated.
thanks!

I don’t have an answer for you. Perhaps someone else knows.

hi,
I found the answer…no need to import any files or anything. just instantiate a WebSocket object in onLoaad and then set the callback functions in start and then write the callback functions anywhere in the program. here is the code in typescript:

@property(WebSocket)
webSocket: WebSocket = null;

onLoad () {
this.webSocket = new WebSocket(“ws://url:8080/server_application_name/server_endpoint”);
}

start () {
this.webSocket.onopen = function(message){ wsOpen(message);};
this.webSocket.onmessage = function(message){ wsGetMessage(message);};
this.webSocket.onclose = function(message){ wsClose(message);};
this.webSocket.onerror = function(message){ wsError(message);};
}
// the callback functions are in javascript
// an important thing to note is that in the callback functions we can’t use this or any global variables
// to store the value of the message. hence in getmessage, I have used localstorage to store the value
// of the message.data which I then extract and use in update()

function wsOpen(message)
{
console.log(“Connection Opened”);
}

function wsGetMessage(message)
{
var price = message.data;
cc.sys.localStorage.setItem(“text”, price);
}

function wsClose(message)
{
console.log(“Connection Closed”);
this.webSocket.close();
}

function wsError(message)
{
console.log(“Error in Websocket Connection”);
}

hope this helps!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.