Auycro

Implement WebSocket to Unity WebGL via Javascript Plugin#1

02 Sep 2015

This guide will introduce you how to implement Unity’s WebGL with WebSocket.

Part1

Prepare Javascript plugin function

First we will prepare the WebSocket library in javascript.
Here is my Javascript plugin for WebSocket, "WebSocket.jslib".

//Copyright (c) 2015 Gumpanat Keardkeawfa
//Licensed under the MIT license
//Websocket Jslib for UnityWebgl
//We will save this file as *.jslib for using in UNITY
var WebSocketJsLib = {
Hello: function(){
window.alert("Hello,world!");
},
InitWebSocket: function(url){
var init_url = Pointer_stringify(url);
window.wsclient = new WebSocket(init_url);
window.wsclient.onopen = function(evt){
console.log("[open]"+init_url);
window.wsclient.send("hello");
};
window.wsclient.onclose = function(evt) {
console.log("[close] "+evt.code+":"+evt.reason);
};
window.wsclient.onmessage = function(evt) {
var received_msg = evt.data;
if (received_msg == "hello") {
window.wsclient.send("hello");
} else {
console.log("[recv] "+received_msg);
SendMessage('WebSocketGameObject', 'RecvString', received_msg);
}
};
window.wsclient.onerror = function(evt) {
var error_msg = evt.data;
console.log("[error] "+error_msg);
SendMessage('WebSocketGameObject', 'ErrorString', "close");
};
},
State: function(){
var status = 0;
if ((typeof window.wsclient !== "undefined")&& (window.wsclient !== null))
status = window.wsclient.readystate;
return status;
},
Send: function(msg){
var message = Pointer_stringify(msg);
if (typeof window.wsclient !== "undefined") {
console.log("[send] "+message);
window.wsclient.send(message);
} else {
console.log("[send-failed] "+message);
}
},
Close: function(){
if ((typeof window.wsclient !== "undefined")&& (window.wsclient !== null))
window.wsclient.close();
}
}
mergeInto(LibraryManager.library, WebSocketJsLib);

As you can see, we already have 5 functions (Hello,InitWebSocket,Send,State,Close) to use in Unity.
In the next part, I will show you how to create GameObject and Script.

Go Part2

Reference: webgl-interactingwithbrowserscripting WebSocket-echo WebSocket