Skip to content

Commit

Permalink
burst optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
psygames committed Mar 4, 2022
1 parent 2221096 commit c24c4a5
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 276 deletions.
42 changes: 35 additions & 7 deletions Assets/UnityWebSocket/Demo/UnityWebSocketDemo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public class UnityWebSocketDemo : MonoBehaviour
private int sendCount;
private int receiveCount;
private Vector2 scrollPos;
private Color green = new Color(0.1f, 1, 0.1f);
private Color red = new Color(1f, 0.1f, 0.1f);
private Color wait = new Color(0.7f, 0.3f, 0.3f);

private void OnGUI()
{
Expand All @@ -23,10 +26,19 @@ private void OnGUI()

WebSocketState state = socket == null ? WebSocketState.Closed : socket.ReadyState;

GUILayout.Label("SDK Version: " + Settings.VERSION, width);
var stateColor = state == WebSocketState.Closed ? "red" : state == WebSocketState.Open ? "#11ff11" : "#aa4444";
var richText = new GUIStyle() { richText = true };
GUILayout.Label(string.Format(" <color=white>State:</color> <color={1}>{0}</color>", state, stateColor), richText);
GUILayout.BeginHorizontal();
GUILayout.Label("SDK Version: " + Settings.VERSION, GUILayout.Width(Screen.width / scale - 100));
GUI.color = green;
GUILayout.Label($"FPS: {fps:F2}", GUILayout.Width(80));
GUI.color = Color.white;
GUILayout.EndHorizontal();

GUILayout.BeginHorizontal();
GUILayout.Label("State: ", GUILayout.Width(36));
GUI.color = WebSocketState.Closed == state ? red : WebSocketState.Open == state ? green : wait;
GUILayout.Label($"{state}", GUILayout.Width(120));
GUI.color = Color.white;
GUILayout.EndHorizontal();

GUI.enabled = state == WebSocketState.Closed;
GUILayout.Label("Address: ", width);
Expand Down Expand Up @@ -116,12 +128,13 @@ private void OnGUI()
private void AddLog(string str)
{
if (!logMessage) return;
if (str.Length > 100) str = str.Substring(0, 100) + "...";
log += str + "\n";
if (log.Length > 4 * 1024)
if (log.Length > 22 * 1024)
{
log = log.Substring(2 * 1024);
log = log.Substring(log.Length - 22 * 1024);
}
scrollPos.y = 10000;
scrollPos.y = int.MaxValue;
}

private void Socket_OnOpen(object sender, OpenEventArgs e)
Expand Down Expand Up @@ -159,5 +172,20 @@ private void OnApplicationQuit()
socket.CloseAsync();
}
}

private int frame = 0;
private float time = 0;
private float fps = 0;
private void Update()
{
frame += 1;
time += Time.deltaTime;
if (time >= 0.5f)
{
fps = frame / time;
frame = 0;
time = 0;
}
}
}
}
22 changes: 4 additions & 18 deletions Assets/UnityWebSocket/Plugins/WebGL/WebSocket.jslib
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ var WebSocketLibrary =
onMessage: null,
onError: null,
onClose: null,

/* Debug mode */
debug: false
},

/**
Expand Down Expand Up @@ -83,8 +80,8 @@ var WebSocketLibrary =
*/
WebSocketAllocate: function(url)
{
var urlStr = Pointer_stringify(url);
var id = webSocketManager.lastId++;
var urlStr = UTF8ToString(url);
var id = ++webSocketManager.lastId;
webSocketManager.instances[id] = {
url: urlStr,
ws: null
Expand Down Expand Up @@ -130,17 +127,12 @@ var WebSocketLibrary =

instance.ws.onopen = function()
{
if (webSocketManager.debug)
console.log("[JSLIB WebSocket] Connected.");
if (webSocketManager.onOpen)
Module.dynCall_vi(webSocketManager.onOpen, instanceId);
};

instance.ws.onmessage = function(ev)
{
if (webSocketManager.debug)
console.log("[JSLIB WebSocket] Received message: ", ev.data);

if (webSocketManager.onMessage === null)
return;

Expand Down Expand Up @@ -200,9 +192,6 @@ var WebSocketLibrary =

instance.ws.onerror = function(ev)
{
if (webSocketManager.debug)
console.log("[JSLIB WebSocket] Error occured.");

if (webSocketManager.onError)
{
var msg = "WebSocket error.";
Expand All @@ -222,9 +211,6 @@ var WebSocketLibrary =

instance.ws.onclose = function(ev)
{
if (webSocketManager.debug)
console.log("[JSLIB WebSocket] Closed, Code: " + ev.code + ", Reason: " + ev.reason);

if (webSocketManager.onClose)
{
var msg = ev.reason;
Expand Down Expand Up @@ -261,7 +247,7 @@ var WebSocketLibrary =
if (instance.ws.readyState === 2) return -4;
if (instance.ws.readyState === 3) return -5;

var reason = ( reasonPtr ? Pointer_stringify(reasonPtr) : undefined );
var reason = ( reasonPtr ? UTF8ToString(reasonPtr) : undefined );
try
{
instance.ws.close(code, reason);
Expand Down Expand Up @@ -305,7 +291,7 @@ var WebSocketLibrary =
if (instance.ws === null) return -3;
if (instance.ws.readyState !== 1) return -6;

instance.ws.send(Pointer_stringify(stringPtr));
instance.ws.send(UTF8ToString(stringPtr));

return 0;
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#if !NET_LEGACY && (UNITY_EDITOR || !UNTIY_WEBGL)
#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL)
using System;
using System.Collections.Generic;
using System.Text;
Expand All @@ -7,7 +7,7 @@
using System.Net.WebSockets;
using System.IO;

namespace UnityWebSocket.NoWebGL
namespace UnityWebSocket
{
public class WebSocket : IWebSocket
{
Expand Down Expand Up @@ -52,6 +52,9 @@ public WebSocket(string address)

public void ConnectAsync()
{
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
WebSocketManager.Instance.Add(this);
#endif
if (socket != null)
{
HandleError(new Exception("Socket is busy."));
Expand Down Expand Up @@ -244,29 +247,87 @@ private void SocketDispose()
private void HandleOpen()
{
Log("OnOpen");
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
HandleEventSync(new OpenEventArgs());
#else
OnOpen?.Invoke(this, new OpenEventArgs());
#endif
}

private void HandleMessage(Opcode opcode, byte[] rawData)
{
Log($"OnMessage, type: {opcode}, size: {rawData.Length}");
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
HandleEventSync(new MessageEventArgs(opcode, rawData));
#else
OnMessage?.Invoke(this, new MessageEventArgs(opcode, rawData));
#endif
}

private void HandleClose(ushort code, string reason)
{
Log($"OnClose, code: {code}, reason: {reason}");
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
HandleEventSync(new CloseEventArgs(code, reason));
#else
OnClose?.Invoke(this, new CloseEventArgs(code, reason));
#endif
}

private void HandleError(Exception exception)
{
Log("OnError, error: " + exception.Message);
#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
HandleEventSync(new ErrorEventArgs(exception.Message));
#else
OnError?.Invoke(this, new ErrorEventArgs(exception.Message));
#endif
}

#if !UNITY_WEB_SOCKET_ENABLE_ASYNC
private readonly Queue<EventArgs> eventQueue = new Queue<EventArgs>();
private readonly object eventQueueLock = new object();
private void HandleEventSync(EventArgs eventArgs)
{
lock (eventQueueLock)
{
eventQueue.Enqueue(eventArgs);
}
}

internal void Update()
{
EventArgs e;
while (eventQueue.Count > 0)
{
lock (eventQueueLock)
{
e = eventQueue.Dequeue();
}

if (e is CloseEventArgs)
{
OnClose?.Invoke(this, e as CloseEventArgs);
WebSocketManager.Instance.Remove(this);
}
else if (e is OpenEventArgs)
{
OnOpen?.Invoke(this, e as OpenEventArgs);
}
else if (e is MessageEventArgs)
{
OnMessage?.Invoke(this, e as MessageEventArgs);
}
else if (e is ErrorEventArgs)
{
OnError?.Invoke(this, e as ErrorEventArgs);
}
}
}
#endif

[System.Diagnostics.Conditional("UNITY_WEB_SOCKET_LOG")]
private void Log(string msg)
static void Log(string msg)
{
UnityEngine.Debug.Log($"<color=yellow>[UnityWebSocket]</color>" +
$"<color=green>[T-{Thread.CurrentThread.ManagedThreadId:D3}]</color>" +
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Collections.Generic;
#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL) && !UNITY_WEB_SOCKET_ENABLE_ASYNC
using System.Collections.Generic;
using UnityEngine;

namespace UnityWebSocket
{
[DefaultExecutionOrder(-10000)]
internal class WebSocketManager : MonoBehaviour
{
private const string rootName = "[UnityWebSocket]";
Expand All @@ -16,7 +18,7 @@ public static WebSocketManager Instance
}
}

void Awake()
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
Expand Down Expand Up @@ -53,3 +55,4 @@ private void Update()
}
}
}
#endif

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading

0 comments on commit c24c4a5

Please sign in to comment.