Skip to content

Commit

Permalink
websocket js support for wegame & code optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
psygames committed Oct 19, 2022
1 parent 9f02edc commit ce7cf5b
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 63 deletions.
102 changes: 50 additions & 52 deletions Assets/UnityWebSocket/Plugins/WebGL/WebSocket.jslib
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ var WebSocketLibrary =
* {
* url: string,
* ws: WebSocket,
* subProtocols: string[],
* binaryType: string,
* subProtocols: string[],
* }
*/
instances: {},
Expand Down Expand Up @@ -79,14 +80,17 @@ var WebSocketLibrary =
*
* @param url Server URL
*/
WebSocketAllocate: function(url)
WebSocketAllocate: function(urlPtr, binaryTypePtr)
{
var urlStr = UTF8ToString(url);
var url = UTF8ToString(urlPtr);
var binaryType = UTF8ToString(binaryTypePtr);
var id = ++webSocketManager.lastId;
webSocketManager.instances[id] = {
url: urlStr,
ws: null
url: url,
ws: null,
binaryType: binaryType
};

return id;
},

Expand All @@ -96,17 +100,18 @@ var WebSocketLibrary =
* @param instanceId Instance ID
* @param protocol Sub Protocol
*/
WebSocketAddSubProtocol: function(instanceId, protocol)
WebSocketAddSubProtocol: function(instanceId, protocolPtr)
{
var instance = webSocketManager.instances[instanceId];
if (!instance) return -1;

var protocolStr = UTF8ToString(protocol);
var protocol = UTF8ToString(protocolPtr);

if(instance.subProtocols == null)
instance.subProtocols = [];

instance.subProtocols.push(protocolStr);
instance.subProtocols.push(protocol);

return 0;
},

Expand Down Expand Up @@ -149,25 +154,23 @@ var WebSocketLibrary =
else
instance.ws = new WebSocket(instance.url);

instance.ws.binaryType = instance.binaryType;

instance.ws.onopen = function()
{
if (webSocketManager.onOpen)
Module.dynCall_vi(webSocketManager.onOpen, instanceId);
Module.dynCall_vi(webSocketManager.onOpen, instanceId);
};

instance.ws.onmessage = function(ev)
{
if (webSocketManager.onMessage === null)
return;

if (ev.data instanceof ArrayBuffer)
{
var dataBuffer = new Uint8Array(ev.data);
var buffer = _malloc(dataBuffer.length);
HEAPU8.set(dataBuffer, buffer);
var array = new Uint8Array(ev.data);
var buffer = _malloc(array.length);
writeArrayToMemory(array, buffer);
try
{
Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, dataBuffer.length);
Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length);
}
finally
{
Expand All @@ -177,21 +180,21 @@ var WebSocketLibrary =
else if (ev.data instanceof Blob)
{
var reader = new FileReader();
reader.addEventListener("loadend", function()
reader.onload = function()
{
var dataBuffer = new Uint8Array(reader.result);
var buffer = _malloc(dataBuffer.length);
HEAPU8.set(dataBuffer, buffer);
var array = new Uint8Array(reader.result);
var buffer = _malloc(array.length);
writeArrayToMemory(array, buffer);
try
{
Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, dataBuffer.length);
Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length);
}
finally
{
reader = null;
_free(buffer);
}
});
};
reader.readAsArrayBuffer(ev.data);
}
else if(typeof ev.data == 'string')
Expand All @@ -216,43 +219,37 @@ var WebSocketLibrary =

instance.ws.onerror = function(ev)
{
if (webSocketManager.onError)
var msg = "WebSocket error.";
var length = lengthBytesUTF8(msg) + 1;
var buffer = _malloc(length);
stringToUTF8(msg, buffer, length);
try
{
var msg = "WebSocket error.";
var length = lengthBytesUTF8(msg) + 1;
var buffer = _malloc(length);
stringToUTF8(msg, buffer, length);
try
{
Module.dynCall_vii(webSocketManager.onError, instanceId, buffer);
}
finally
{
_free(buffer);
}
Module.dynCall_vii(webSocketManager.onError, instanceId, buffer);
}
finally
{
_free(buffer);
}
};

instance.ws.onclose = function(ev)
{
if (webSocketManager.onClose)
var msg = ev.reason;
var length = lengthBytesUTF8(msg) + 1;
var buffer = _malloc(length);
stringToUTF8(msg, buffer, length);
try
{
var msg = ev.reason;
var length = lengthBytesUTF8(msg) + 1;
var buffer = _malloc(length);
stringToUTF8(msg, buffer, length);
try
{
Module.dynCall_viii(webSocketManager.onClose, instanceId, ev.code, buffer);
}
finally
{
_free(buffer);
}
Module.dynCall_viii(webSocketManager.onClose, instanceId, ev.code, buffer);
}
finally
{
_free(buffer);
}

instance.ws = null;
};

return 0;
},

Expand Down Expand Up @@ -280,6 +277,7 @@ var WebSocketLibrary =
{
return -7;
}

return 0;
},

Expand All @@ -297,7 +295,7 @@ var WebSocketLibrary =
if (instance.ws === null) return -3;
if (instance.ws.readyState !== 1) return -6;

instance.ws.send(HEAPU8.slice(bufferPtr, bufferPtr + length));
instance.ws.send(buffer.slice(bufferPtr, bufferPtr + length));

return 0;
},
Expand Down Expand Up @@ -329,7 +327,7 @@ var WebSocketLibrary =
{
var instance = webSocketManager.instances[instanceId];
if (!instance) return -1;
if (instance.ws === null) return 3;
if (instance.ws === null) return 3; // socket null as closed

return instance.ws.readyState;
}
Expand Down
15 changes: 14 additions & 1 deletion Assets/UnityWebSocket/Scripts/Runtime/Core/IWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,24 @@ public interface IWebSocket
/// It indicates the current state of the connection.
/// </para>
/// <para>
/// The default value is <see cref="WebSocketState.Connecting"/>.
/// The default value is <see cref="WebSocketState.Closed"/>.
/// </para>
/// </value>
WebSocketState ReadyState { get; }

/// <summary>
/// Gets the current binaryType of the connection, supported on WEBGL platform only.
/// </summary>
/// <value>
/// <para>
/// It indicates the current binaryType of the connection.
/// </para>
/// <para>
/// The default value is "arraybuffer", options: "blob" or "arraybuffer".
/// </para>
/// </value>
string BinaryType { get; set; }

/// <summary>
/// Occurs when the WebSocket connection has been established.
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions Assets/UnityWebSocket/Scripts/Runtime/Core/Settings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace UnityWebSocket
namespace UnityWebSocket
{
public static class Settings
{
Expand All @@ -7,6 +7,6 @@ public static class Settings
public const string QQ_GROUP_LINK = "https://qm.qq.com/cgi-bin/qm/qr?k=KcexYJ9aYwogFXbj2aN0XHH5b2G7ICmd";
public const string EMAIL = "799329256@qq.com";
public const string AUHTOR = "psygames";
public const string VERSION = "2.6.6";
public const string VERSION = "2.7.0";
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL)
#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL)
using System;
using System.Collections.Generic;
using System.Text;
Expand Down Expand Up @@ -37,6 +37,8 @@ public WebSocketState ReadyState
}
}

public string BinaryType { get; set; } = "arraybuffer";

public event EventHandler<OpenEventArgs> OnOpen;
public event EventHandler<CloseEventArgs> OnClose;
public event EventHandler<ErrorEventArgs> OnError;
Expand Down Expand Up @@ -278,7 +280,7 @@ private void HandleOpen()

private void HandleMessage(Opcode opcode, byte[] rawData)
{
Log($"OnMessage, type: {opcode}, size: {rawData.Length}");
Log($"OnMessage, type: {opcode}, size: {rawData.Length}\n{BitConverter.ToString(rawData)}");
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
HandleEventSync(new MessageEventArgs(opcode, rawData));
#else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class WebSocket : IWebSocket
public string Address { get; private set; }
public string[] SubProtocols { get; private set; }
public WebSocketState ReadyState { get { return (WebSocketState)WebSocketManager.WebSocketGetState(instanceId); } }
public string BinaryType { get; set; } = "arraybuffer";

public event EventHandler<OpenEventArgs> OnOpen;
public event EventHandler<CloseEventArgs> OnClose;
Expand Down Expand Up @@ -38,15 +39,15 @@ public WebSocket(string address, string[] subProtocols)

internal void AllocateInstance()
{
instanceId = WebSocketManager.AllocateInstance(this.Address);
instanceId = WebSocketManager.AllocateInstance(this.Address, this.BinaryType);
Log($"Allocate socket with instanceId: {instanceId}");
if (this.SubProtocols == null) return;
foreach (var protocol in this.SubProtocols)
{
if (string.IsNullOrEmpty(protocol)) continue;
Log($"Add Sub Protocol {protocol}, with instanceId: {instanceId}");
int code = WebSocketManager.WebSocketAddSubProtocol(instanceId, protocol);
if (code < 0)
if (code < 0)
{
HandleOnError(GetErrorMessageFromCode(code));
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ internal static class WebSocketManager
public static extern int WebSocketSend(int instanceId, byte[] dataPtr, int dataLength);

[DllImport("__Internal")]
public static extern int WebSocketSendStr(int instanceId, string dataPtr);
public static extern int WebSocketSendStr(int instanceId, string data);

[DllImport("__Internal")]
public static extern int WebSocketGetState(int instanceId);

/* WebSocket JSLIB callback setters and other functions */
[DllImport("__Internal")]
public static extern int WebSocketAllocate(string url);
public static extern int WebSocketAllocate(string url, string binaryType);

[DllImport("__Internal")]
public static extern int WebSocketAddSubProtocol(int instanceId, string protocol);
Expand Down Expand Up @@ -127,10 +127,10 @@ public static void DelegateOnCloseEvent(int instanceId, int closeCode, IntPtr re
}
}

internal static int AllocateInstance(string address)
internal static int AllocateInstance(string address, string binaryType)
{
if (!isInitialized) Initialize();
return WebSocketAllocate(address);
return WebSocketAllocate(address, binaryType);
}

internal static void Add(WebSocket socket)
Expand Down

0 comments on commit ce7cf5b

Please sign in to comment.