public void Log(object message, ErrorLevel level, SocketKey key = null) { lock (_logLock) { entries.Add(new LogEntry() { timestamp = DateTime.Now, level = level, key = key, message = MsgFmt(message) }); } switch (level) { case ErrorLevel.Info: Debug.Log(KeyFmt(key) + message); break; case ErrorLevel.Warning: Debug.LogWarning(KeyFmt(key) + message); break; case ErrorLevel.Error: Debug.LogError(KeyFmt(key) + message); break; } }
public void Dispatch(string messageType, string messageData, SocketKey key) { var signalType = typeMap.Get(messageType); if (signalType == null) { debug.LogWarning("No message type for " + messageType, key); return; } BaseSignal signal = null; try { signal = binder.GetInstance(signalType) as BaseSignal; } catch(Exception ex) { debug.LogError("Could not get get instance of signal for " + messageType + " " + signalType + " " + ex.ToString(), key); return; } if (signal != null) { var signalDataTypes = signal.GetTypes(); bool attachKey = false; if(signalDataTypes.Count == 2 && signalDataTypes[1] == typeof(SocketKey)) { attachKey = true; } else if (signalDataTypes.Count != 1) { debug.LogError("Signal can only have one type of data to dispatch", key); return; } var signalDataType = signalDataTypes[0]; var deserializedData = JsonConvert.DeserializeObject(messageData, signalDataType); if (deserializedData == null) { debug.LogWarning("Null data for " + messageType, key); return; } object[] signalData; if (attachKey) { signalData = new object[] { deserializedData, key }; } else { signalData = new object[] { deserializedData }; } var methodInfo = signalType .GetMethods() .Where(m => m.Name == "Dispatch") .First(); methodInfo.Invoke(signal, signalData ); } else { debug.LogError("Could not find signal to dispatch from message type " + messageType, key); } }
private void onLoggedIn(LoginStatusModel status, SocketKey key) { view.enabled = false; view.gameObject.SetActive(false); needLoginSignal.RemoveListener(onNeedLogin); failedAuth.RemoveListener(onFailAuth); loggedInSignal.RemoveListener(onLoggedIn); }
private void onPlayerFetched(PlayerModel p, SocketKey key) { if (!loginStatuses.ContainsKey(key)) { debug.LogWarning("Key not found in check login statuses"); return; } loginStatuses[key].checkSuccess = false; }
private void onLoggedIn(LoginStatusModel status, SocketKey key) { //start checking for successful login, if one is not found (by the player fetched) //resend the login signal to retrigger the fetch player command loginStatuses[key] = new LoginWatch() { loginStatus = status, checkSuccess = true }; }
private void onFetchComplete(PlayerModel player, SocketKey key) { if (player == null) { debug.LogError("Failed Fetching Player", key); } else { debug.Log("Player Fetched", key); var playerModel = playersModel.GetByClientId(key.clientId); //kinda nasty save of the couple properties that need to be saved on the original player model //that won't be coming across the wire var clientId = playerModel.clientId; var token = playerModel.token; player.CopyProperties(playerModel); playerModel.clientId = clientId; playerModel.token = token; playerModel.isLocal = true; socketService.Disconnect(key.clientId, "auth"); } }
private void onTokenComplete(string token, SocketKey key) { if (string.IsNullOrEmpty(token)) { debug.LogError("Failed Authenticate", key); failedAuth.Dispatch(); needLoginSignal.Dispatch(); } else { debug.Log("Authenticated", key); var player = playersModel.GetByClientId(key.clientId); if (player == null) { playersModel.players.Add(new PlayerModel() { clientId = key.clientId, token = token }); } PlayerPrefs.SetString(CtacConst.playerToken, token); } }
private IEnumerator ConnectAndRequest(SocketKey key, string methodName, object data) { yield return root.StartCoroutine(SocketConnect(key)); yield return root.StartCoroutine(MakeRequest(key, methodName, data)); }
public void Request(SocketKey key, string methodName, object data = null) { if (key == null) { debug.LogError("Cannot make request with a null SocketKey"); } var ws = sockets.Get(key); if (ws != null) { connectSignal.RemoveAllListeners(); root.StartCoroutine(MakeRequest(key, methodName, data)); } else { root.StartCoroutine(ConnectAndRequest(key, methodName, data)); } }
public void Disconnect(SocketKey key) { var ws = sockets.Get(key); if (ws == null) { debug.LogWarning("Trying to disconnect from disconnected socket", key); } ws.Close(CloseStatusCode.Normal, "Requested Disconnect"); sockets.Remove(key); }
private void onMessage(MessageModel message, SocketKey key) { view.updateText(message.message, message.duration ?? 1f); }
private void onSocketError(SocketKey key, object sender, ErrorEventArgs e) { debug.Log("Socket Error: " + e.Message + " " + e.Exception.Message + "\n" + e.Exception.StackTrace, key); errorSignal.Dispatch(key, e.Message); }
private string KeyFmt(SocketKey key) { if(key == null) return ""; return key.clientId.ToShort() + " " + key.componentName + " "; }
public void LogWarning(object message, SocketKey key = null) { Log(message, ErrorLevel.Warning, key); }
private void onFetchComplete(PlayerModel player, SocketKey key) { socketService.Request(key.clientId, "gamelist", "token", player.token); }
public void onDestroyed(PieceDestroyedModel m, SocketKey k) { addGenericHistory(m.pieceId, m.activatingPieceId); }
public void onCode(AttachCodeModel m, SocketKey k) { addGenericHistory(m.pieceId, m.activatingPieceId); }
private IEnumerator MakeRequest(SocketKey key, string methodName, object data) { var ws = sockets.Get(key); if (ws.ReadyState != WebSocketState.Open) { debug.LogError("Trying to make a request to disconnected web socket", key); yield return null; } string message = methodName + " " + JsonConvert.SerializeObject(data); debug.Log("Send: " + message, ErrorLevel.NetSend, key); ws.Send(message); yield return null; }
private void onSocketClose(SocketKey key, object sender, CloseEventArgs e) { debug.Log("Socket Close: " + key.clientId.ToShort() + " " + key.componentName + " " + e.Reason, key); disconnectSignal.Dispatch(key); }
private void onSocketOpen(SocketKey key, object sender, EventArgs e) { debug.Log("Socket Open For " + key.clientId.ToShort() + " " + key.componentName, key); connectSignal.Dispatch(key); }
private void onSocketMessage(SocketKey key, object sender, MessageEventArgs e) { debug.Log("Msg: " + e.Data, ErrorLevel.NetRecv, key); //chop it up and convert to appropriate signal based on header var delimiterIndex = e.Data.IndexOf(' '); string messageType = e.Data.Substring(0, delimiterIndex); string messageData = e.Data.Substring(delimiterIndex + 1); signalDispatcher.ScheduleSignal( new SignalData() { messageType = messageType, messageData = messageData, key = key } ); }
private void tokenReceived(string token, SocketKey key) { //decode and mark try login statuses to stop checking var splitToken = token.Split('.'); if (splitToken.Length != 3) { debug.LogError("Login token appears invalid " + token, key); return; } var payload = splitToken[1]; //you have to pad base 64 strings with ='s so the length is a multiple of 4 string dummyData = payload.Trim().Replace(" ", "+"); if (dummyData.Length % 4 > 0) dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '='); byte[] data = Convert.FromBase64String(dummyData); var jsonWebToken = Encoding.UTF8.GetString(data); var payloadObj = JsonConvert.DeserializeObject<TokenPayload>(jsonWebToken); if (payloadObj == null || payloadObj.sub == null || string.IsNullOrEmpty(payloadObj.sub.email)) { debug.LogError("Could not get login info from token " + jsonWebToken, key); return; } //find right try login status to mark var loginStatus = tryLoginStatuses.Where(x => x.Key.username == payloadObj.sub.email).FirstOrDefault(); if (loginStatus.Key != null) { tryLoginStatuses[loginStatus.Key] = false; } }
private IEnumerator SocketConnect(SocketKey key) { var url = componentModel.getComponentWSURL(key.componentName); if (string.IsNullOrEmpty(url)) { debug.LogError("Could not find url to open socket for component " + key.componentName, key); yield return null; } var ws = new WebSocket(url); sockets[key] = ws; ws.WaitTime = new TimeSpan(0, 0, 5); ws.OnMessage += (o, e) => onSocketMessage(key, o, e); ws.OnError += (o, e) => onSocketError(key, o, e); ws.OnOpen += (o, e) => onSocketOpen(key, o, e); ws.OnClose += (o, e) => onSocketClose(key, o, e); debug.Log("Attempting connection to " + url, key); ws.ConnectAsync(); int i = 0; while (i < 1000) { i++; if (ws.ReadyState == WebSocketState.Open) break; yield return null; } }
public void Log(object message, SocketKey key = null) { Log(message, ErrorLevel.Info, key); }