public void OnConnect() { DebugConsole.Log("Game Server connected"); OnConnectedTCP.Invoke(); }
///// <summary> ///// Gets called when the session is first launched, does some setup ///// </summary> ///// <param name="obj">Takes a CampaignGameStarter Object</param> //private void OnSessionLaunched(CampaignGameStarter obj) { // //Dconsole.Instance().Log(this, "attempting to hook menu"); // try { // //attempt to add the recruiter menu // this.AddRecruiterMenu(obj); // this.AddProcurementMenu(obj); // } catch (Exception ex) { // //Dconsole.Instance().Log(this, ex.ToString()); // } //} //private bool addLeaveConditional(MenuCallbackArgs args) { // args.optionLeaveType = GameMenuOption.LeaveType.Leave; // return true; //} //private void switchToVillageMenu(MenuCallbackArgs args) { // GameMenu.SwitchToMenu("castle"); //} ///// <summary> ///// The Recruiter menu gets spliced into the game here ///// </summary> ///// <param name="obj"></param> //public void AddRecruiterMenu(CampaignGameStarter obj) { // GameMenuOption.OnConditionDelegate recruiterDelegate = delegate (MenuCallbackArgs args) { // args.optionLeaveType = GameMenuOption.LeaveType.Recruit; // return Settlement.CurrentSettlement.OwnerClan == Clan.PlayerClan; // }; // GameMenuOption.OnConsequenceDelegate recruiterConsequencesDelegate = delegate (MenuCallbackArgs args) { // GameMenu.SwitchToMenu("recruiter_hire_menu"); // }; // obj.AddGameMenu("recruiter_hire_menu", "Select a faction to recruit from.", null, GameOverlays.MenuOverlayType.None, GameMenu.MenuFlags.none); // //Adds "Hire A recruiter" option to town keep and castle menus // obj.AddGameMenuOption("town_keep", "recruiter_buy_recruiter", "Hire a recruiter.", recruiterDelegate, recruiterConsequencesDelegate, false, 4, false); // obj.AddGameMenuOption("castle", "recruiter_buy_recruiter", "Hire a Recruiter", recruiterDelegate, recruiterConsequencesDelegate, false, 4, false); // //This adds the pay menu option to the faction menu // obj.AddGameMenuOption("recruiter_hire_menu", "recruiter_pay_small", "Pay 500.", delegate (MenuCallbackArgs args) // { // args.optionLeaveType = GameMenuOption.LeaveType.Recruit; // string stringId = Settlement.CurrentSettlement.StringId; // int cost = 500; // bool flag = cost >= Hero.MainHero.Gold; // return !flag; // }, delegate (MenuCallbackArgs args) // { // string stringId = Settlement.CurrentSettlement.StringId; // int cost = 500; // bool flag = cost <= Hero.MainHero.Gold; // if (flag) { // GiveGoldAction.ApplyForCharacterToSettlement(Hero.MainHero, Settlement.CurrentSettlement, cost, false); // } // GameMenu.SwitchToMenu("castle"); // }, false, -1, false); // obj.AddGameMenuOption("recruiter_hire_menu", "recruiter_leave", "Nevermind.", new GameMenuOption.OnConditionDelegate(this.addLeaveConditional), new GameMenuOption.OnConsequenceDelegate(this.switchToVillageMenu), false, -1, false); //} //public void AddProcurementMenu(CampaignGameStarter obj) { // GameMenuOption.OnConditionDelegate procurementDelegate = delegate (MenuCallbackArgs args) { // args.optionLeaveType = GameMenuOption.LeaveType.Trade; // return Settlement.CurrentSettlement.OwnerClan == Clan.PlayerClan; // }; // GameMenuOption.OnConsequenceDelegate procurementConsequencesDelegate = delegate (MenuCallbackArgs args) { // GameMenu.SwitchToMenu("procurement_menu"); // }; // obj.AddGameMenu("procurement_menu", "Select Items to procure", null, GameOverlays.MenuOverlayType.None, GameMenu.MenuFlags.none); // //Adds "Procure War Materials" option to town keep // obj.AddGameMenuOption("town_keep", "procurement_menu", "Procure War Materials.", procurementDelegate, procurementConsequencesDelegate, false, 4, false); // obj.AddGameMenuOption("procurement_menu", "recruiter_leave", "Nevermind.", new GameMenuOption.OnConditionDelegate(this.addLeaveConditional), new GameMenuOption.OnConsequenceDelegate(this.switchToVillageMenu), false, -1, false); //} private void OnPlayerLevelUp(Hero hero, bool notsure) { DebugConsole.Log(this, "Player level up"); DebugConsole.Log(this, hero.FirstName.ToString() + " level up: " + notsure.ToString()); }
private void ClientInitRequest(NetIncomingMessage inc) { DebugConsole.Log("Received client init request"); if (ConnectedClients.Find(c => c.Connection == inc.SenderConnection) != null) { //this client was already authenticated //another init request means they didn't get any update packets yet DebugConsole.Log("Client already connected, ignoring..."); return; } UnauthenticatedClient unauthClient = unauthenticatedClients.Find(uc => uc.Connection == inc.SenderConnection); if (unauthClient == null) { //client did not ask for nonce first, can't authorize inc.SenderConnection.Disconnect(DisconnectReason.AuthenticationRequired.ToString()); if (unauthClient.SteamID > 0) { Steam.SteamManager.StopAuthSession(unauthClient.SteamID); } return; } if (serverSettings.HasPassword && inc.SenderConnection != OwnerConnection) { //decrypt message and compare password string clPw = inc.ReadString(); if (!serverSettings.IsPasswordCorrect(clPw, unauthClient.Nonce)) { unauthClient.FailedAttempts++; if (unauthClient.FailedAttempts > 3) { //disconnect and ban after too many failed attempts serverSettings.BanList.BanPlayer("Unnamed", unauthClient.Connection.RemoteEndPoint.Address, "DisconnectMessage.TooManyFailedLogins", duration: null); DisconnectUnauthClient(inc, unauthClient, DisconnectReason.TooManyFailedLogins, ""); Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " has been banned from the server (too many wrong passwords)", ServerLog.MessageType.Error); DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " has been banned from the server (too many wrong passwords)", Color.Red); return; } else { //not disconnecting the player here, because they'll still use the same connection and nonce if they try logging in again NetOutgoingMessage reject = server.CreateMessage(); reject.Write((byte)ServerPacketHeader.AUTH_FAILURE); reject.Write("Wrong password! You have " + Convert.ToString(4 - unauthClient.FailedAttempts) + " more attempts before you're banned from the server."); Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " failed to join the server (incorrect password)", ServerLog.MessageType.Error); DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " failed to join the server (incorrect password)", Color.Red); CompressOutgoingMessage(reject); server.SendMessage(reject, unauthClient.Connection, NetDeliveryMethod.Unreliable); unauthClient.AuthTimer = 10.0f; return; } } } string clVersion = inc.ReadString(); UInt16 contentPackageCount = inc.ReadUInt16(); List <string> contentPackageNames = new List <string>(); List <string> contentPackageHashes = new List <string>(); for (int i = 0; i < contentPackageCount; i++) { string packageName = inc.ReadString(); string packageHash = inc.ReadString(); contentPackageNames.Add(packageName); contentPackageHashes.Add(packageHash); if (contentPackageCount == 0) { DebugConsole.Log("Client is using content package " + (packageName ?? "null") + " (" + (packageHash ?? "null" + ")")); } } if (contentPackageCount == 0) { DebugConsole.Log("Client did not list any content packages."); } string clName = Client.SanitizeName(inc.ReadString()); if (string.IsNullOrWhiteSpace(clName)) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NoName, ""); Log(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " couldn't join the server (no name given)", ServerLog.MessageType.Error); DebugConsole.NewMessage(inc.SenderConnection.RemoteEndPoint.Address.ToString() + " couldn't join the server (no name given)", Color.Red); return; } if (clVersion != GameMain.Version.ToString()) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.InvalidVersion, $"DisconnectMessage.InvalidVersion~[version]={GameMain.Version.ToString()}~[clientversion]={clVersion}"); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (wrong game version)", ServerLog.MessageType.Error); DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (wrong game version)", Color.Red); return; } //check if the client is missing any of the content packages the server requires List <ContentPackage> missingPackages = new List <ContentPackage>(); foreach (ContentPackage contentPackage in GameMain.SelectedPackages) { if (!contentPackage.HasMultiplayerIncompatibleContent) { continue; } bool packageFound = false; for (int i = 0; i < contentPackageCount; i++) { if (contentPackageNames[i] == contentPackage.Name && contentPackageHashes[i] == contentPackage.MD5hash.Hash) { packageFound = true; break; } } if (!packageFound) { missingPackages.Add(contentPackage); } } if (missingPackages.Count == 1) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.MissingContentPackage, $"DisconnectMessage.MissingContentPackage~[missingcontentpackage]={GetPackageStr(missingPackages[0])}"); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (missing content package " + GetPackageStr(missingPackages[0]) + ")", ServerLog.MessageType.Error); return; } else if (missingPackages.Count > 1) { List <string> packageStrs = new List <string>(); missingPackages.ForEach(cp => packageStrs.Add(GetPackageStr(cp))); DisconnectUnauthClient(inc, unauthClient, DisconnectReason.MissingContentPackage, $"DisconnectMessage.MissingContentPackages~[missingcontentpackages]={string.Join(", ", packageStrs)}"); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (missing content packages " + string.Join(", ", packageStrs) + ")", ServerLog.MessageType.Error); return; } string GetPackageStr(ContentPackage contentPackage) { return("\"" + contentPackage.Name + "\" (hash " + contentPackage.MD5hash.ShortHash + ")"); } //check if the client is using any contentpackages that are not compatible with the server List <Pair <string, string> > incompatiblePackages = new List <Pair <string, string> >(); for (int i = 0; i < contentPackageNames.Count; i++) { if (!GameMain.Config.SelectedContentPackages.Any(cp => cp.Name == contentPackageNames[i] && cp.MD5hash.Hash == contentPackageHashes[i])) { incompatiblePackages.Add(new Pair <string, string>(contentPackageNames[i], contentPackageHashes[i])); } } if (incompatiblePackages.Count == 1) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.IncompatibleContentPackage, $"DisconnectMessage.IncompatibleContentPackage~[incompatiblecontentpackage]={GetPackageStr2(incompatiblePackages[0])}"); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (incompatible content package " + GetPackageStr2(incompatiblePackages[0]) + ")", ServerLog.MessageType.Error); return; } else if (incompatiblePackages.Count > 1) { List <string> packageStrs = new List <string>(); incompatiblePackages.ForEach(cp => packageStrs.Add(GetPackageStr2(cp))); DisconnectUnauthClient(inc, unauthClient, DisconnectReason.IncompatibleContentPackage, $"DisconnectMessage.IncompatibleContentPackages~[incompatiblecontentpackages]={string.Join(", ", packageStrs)}"); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (incompatible content packages " + string.Join(", ", packageStrs) + ")", ServerLog.MessageType.Error); return; } string GetPackageStr2(Pair <string, string> nameAndHash) { return("\"" + nameAndHash.First + "\" (hash " + Md5Hash.GetShortHash(nameAndHash.Second) + ")"); } if (!serverSettings.Whitelist.IsWhiteListed(clName, inc.SenderConnection.RemoteEndPoint.Address)) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NotOnWhitelist, ""); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (not in whitelist)", ServerLog.MessageType.Error); DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (not in whitelist)", Color.Red); return; } if (!Client.IsValidName(clName, this)) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.InvalidName, ""); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (invalid name)", ServerLog.MessageType.Error); DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (invalid name)", Color.Red); return; } if (inc.SenderConnection != OwnerConnection && Homoglyphs.Compare(clName.ToLower(), Name.ToLower())) { DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NameTaken, ""); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name taken by the server)", ServerLog.MessageType.Error); DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name taken by the server)", Color.Red); return; } Client nameTaken = ConnectedClients.Find(c => Homoglyphs.Compare(c.Name.ToLower(), clName.ToLower())); if (nameTaken != null) { if (nameTaken.Connection.RemoteEndPoint.Address.ToString() == inc.SenderEndPoint.Address.ToString()) { //both name and IP address match, replace this player's connection nameTaken.Connection.Disconnect(DisconnectReason.SessionTaken.ToString()); nameTaken.Connection = unauthClient.Connection; nameTaken.InitClientSync(); //reinitialize sync ids because this is a new connection unauthenticatedClients.Remove(unauthClient); unauthClient = null; return; } else { //can't authorize this client DisconnectUnauthClient(inc, unauthClient, DisconnectReason.NameTaken, ""); Log(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name already taken)", ServerLog.MessageType.Error); DebugConsole.NewMessage(clName + " (" + inc.SenderConnection.RemoteEndPoint.Address.ToString() + ") couldn't join the server (name already taken)", Color.Red); return; } } //new client Client newClient = new Client(clName, GetNewClientID()); newClient.InitClientSync(); newClient.Connection = unauthClient.Connection; newClient.SteamID = unauthClient.SteamID; unauthenticatedClients.Remove(unauthClient); unauthClient = null; ConnectedClients.Add(newClient); LastClientListUpdateID++; if (newClient.Connection == OwnerConnection) { newClient.GivePermission(ClientPermissions.All); newClient.PermittedConsoleCommands.AddRange(DebugConsole.Commands); GameMain.Server.UpdateClientPermissions(newClient); GameMain.Server.SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient); } GameMain.Server.SendChatMessage($"ServerMessage.JoinedServer~[client]={clName}", ChatMessageType.Server, null); var savedPermissions = serverSettings.ClientPermissions.Find(cp => cp.SteamID > 0 ? cp.SteamID == newClient.SteamID : newClient.IPMatches(cp.IP)); if (savedPermissions != null) { newClient.SetPermissions(savedPermissions.Permissions, savedPermissions.PermittedCommands); } else { var defaultPerms = PermissionPreset.List.Find(p => p.Name == "None"); if (defaultPerms != null) { newClient.SetPermissions(defaultPerms.Permissions, defaultPerms.PermittedCommands); } else { newClient.SetPermissions(ClientPermissions.None, new List <DebugConsole.Command>()); } } }
private void HandleDataMessage(IReadMessage inc) { if (!isActive) { return; } UInt64 recipientSteamId = inc.ReadUInt64(); DeliveryMethod deliveryMethod = (DeliveryMethod)inc.ReadByte(); int p2pDataStart = inc.BytePosition; byte incByte = inc.ReadByte(); bool isCompressed = (incByte & (byte)PacketHeader.IsCompressed) != 0; bool isConnectionInitializationStep = (incByte & (byte)PacketHeader.IsConnectionInitializationStep) != 0; bool isDisconnectMessage = (incByte & (byte)PacketHeader.IsDisconnectMessage) != 0; bool isServerMessage = (incByte & (byte)PacketHeader.IsServerMessage) != 0; bool isHeartbeatMessage = (incByte & (byte)PacketHeader.IsHeartbeatMessage) != 0; if (recipientSteamId != selfSteamID) { if (!isServerMessage) { DebugConsole.ThrowError("Received non-server message meant for remote peer"); return; } RemotePeer peer = remotePeers.Find(p => p.SteamID == recipientSteamId); if (peer == null) { return; } if (isDisconnectMessage) { DisconnectPeer(peer, inc.ReadString()); return; } Steamworks.P2PSend sendType; switch (deliveryMethod) { case DeliveryMethod.Reliable: case DeliveryMethod.ReliableOrdered: //the documentation seems to suggest that the Reliable send type //enforces packet order (TODO: verify) sendType = Steamworks.P2PSend.Reliable; break; default: sendType = Steamworks.P2PSend.Unreliable; break; } byte[] p2pData; if (isConnectionInitializationStep) { p2pData = new byte[inc.LengthBytes - p2pDataStart + 8]; p2pData[0] = inc.Buffer[p2pDataStart]; Lidgren.Network.NetBitWriter.WriteUInt64(SteamManager.CurrentLobbyID, 64, p2pData, 8); Array.Copy(inc.Buffer, p2pDataStart + 1, p2pData, 9, inc.LengthBytes - p2pDataStart - 1); } else { p2pData = new byte[inc.LengthBytes - p2pDataStart]; Array.Copy(inc.Buffer, p2pDataStart, p2pData, 0, p2pData.Length); } if (p2pData.Length + 4 >= MsgConstants.MTU) { DebugConsole.Log("WARNING: message length comes close to exceeding MTU, forcing reliable send (" + p2pData.Length.ToString() + " bytes)"); sendType = Steamworks.P2PSend.Reliable; } bool successSend = Steamworks.SteamNetworking.SendP2PPacket(recipientSteamId, p2pData, p2pData.Length, 0, sendType); sentBytes += p2pData.Length; if (!successSend) { if (sendType != Steamworks.P2PSend.Reliable) { DebugConsole.Log("WARNING: message couldn't be sent unreliably, forcing reliable send (" + p2pData.Length.ToString() + " bytes)"); sendType = Steamworks.P2PSend.Reliable; successSend = Steamworks.SteamNetworking.SendP2PPacket(recipientSteamId, p2pData, p2pData.Length, 0, sendType); sentBytes += p2pData.Length; } if (!successSend) { DebugConsole.AddWarning("Failed to send message to remote peer! (" + p2pData.Length.ToString() + " bytes)"); } } } else { if (isDisconnectMessage) { DebugConsole.ThrowError("Received disconnect message from owned server"); return; } if (!isServerMessage) { DebugConsole.ThrowError("Received non-server message from owned server"); return; } if (isHeartbeatMessage) { return; //timeout is handled by Lidgren, ignore this message } if (isConnectionInitializationStep) { IWriteMessage outMsg = new WriteOnlyMessage(); outMsg.Write(selfSteamID); outMsg.Write(selfSteamID); outMsg.Write((byte)(PacketHeader.IsConnectionInitializationStep)); outMsg.Write(Name); byte[] msgToSend = (byte[])outMsg.Buffer.Clone(); Array.Resize(ref msgToSend, outMsg.LengthBytes); ChildServerRelay.Write(msgToSend); return; } else { if (initializationStep != ConnectionInitialization.Success) { OnInitializationComplete?.Invoke(); initializationStep = ConnectionInitialization.Success; } UInt16 length = inc.ReadUInt16(); IReadMessage msg = new ReadOnlyMessage(inc.Buffer, isCompressed, inc.BytePosition, length, ServerConnection); OnMessageReceived?.Invoke(msg); return; } } }
// Use this for initialization void Start() { // 初始化ProtoNet if (m_net == null) { m_login = false; m_net = new ProtoNet(); // 增加前台支持的网络包类型 m_net.Add(Constants.Lion_QuickLoginInfo, LionUserInfo.Parser); m_net.Add(Constants.Lion_Redirect, RedirectResp.Parser); m_net.Add(Constants.Lion_GetProfile, LionUserInfo.Parser); m_net.Add(Constants.Lion_UpdateProfile, Status.Parser); m_net.Add(Constants.Lion_GetTigerStat, TigerStat.Parser); m_net.Add(Constants.Lion_GetFriends, LongArray.Parser); m_net.Add(Constants.Lion_GetFriendRequests, LongArray.Parser); m_net.Add(Constants.Lion_AddFriend, Status.Parser); m_net.Add(Constants.Lion_DeleteFriend, Status.Parser); m_net.Add(Constants.Lion_AcceptFriend, Status.Parser); m_net.Add(Constants.Lion_IgnoreFriend, Status.Parser); m_net.Add(Constants.Lion_GetFriendSummary, FriendSummaryList.Parser); m_net.Add(Constants.Lion_NotifyWeeklyLogin, IntValue.Parser); m_net.Add(Constants.Lion_TakeLoginBonus, LongArray.Parser); m_net.Add(Constants.Lion_NotifyFreeBonus, LongValue.Parser); m_net.Add(Constants.Lion_TakeFreeBonus, LongArray.Parser); m_net.Add(Constants.Lion_BuyItem, Status.Parser); m_net.Add(Constants.Lion_GetItems, UserItemList.Parser); m_net.Add(Constants.Lion_Register, Status.Parser); m_net.Add(Constants.Lion_ModPass, Status.Parser); m_net.Add(Constants.Lion_RefreshGold, LongValue.Parser); m_net.Add(Constants.Lion_GetShopItems, ShopList.Parser); m_net.Add(Constants.Lion_BroadcastSystemMessage, StringValue.Parser); m_net.Add(-2, null); m_net.Add(Constants.Reconnect, null); m_net.Add(Constants.Error, Status.Parser); m_net.Name = "Reception"; } if (!m_login) { // 启动登录 Lobby lobby = Lobby.getInstance(); DebugConsole.Log("Loading start:" + lobby.Domain); if (lobby.Domain == "") { SceneManager.LoadSceneAsync("sloading"); } else { DebugConsole.Log("Loading start2:" + lobby.Domain); if (false == m_net.Init(lobby.Domain, lobby.Port)) { // 这里不重连,在发送请求失败后再重连 DebugConsole.Log("Reception:Client init failed!"); } QuickLogin(); } } else { UpdateUserInfoUI(); } // 刷新倒计时 UpdateCountDown(); for (int i = 0; i < Constants.LobbyBtn_Strings.Length; ++i) { string btnName = Constants.LobbyBtn_Strings[i]; m_btnIndexDict.Add(btnName, i); GameObject btnObj = GameObject.Find(btnName); Button btn = btnObj.GetComponent <Button>(); btn.onClick.AddListener(delegate() { this.OnClick(btnObj); }); } }
void OnClick(GameObject sender) { Tools.PlayAudio(Constants.Audio.Audio_LobbyClickButton); DebugConsole.Log(sender.name); int btnIndex = GetBtn(sender.name); if (btnIndex < 0) { DebugConsole.Log("Cant find button:" + sender.name); return; } switch ((DialogBtn)btnIndex) { case DialogBtn.Close: { GameObject btnObj = GameObject.Find(DialogName); if (null == btnObj) { DebugConsole.Log("null"); } else { DebugConsole.Log("DoHide"); DoHide(btnObj); } } break; /* * case DialogBtn.ProfileOn: * case DialogBtn.RecordsOn: * { * m_profileOn = !m_profileOn; * // 若是老虎机统计信息,这里需要手动获取一次 * if (!m_profileOn) * { * Reception recp = GameObject.Find("Reception").GetComponent<Reception>(); * recp.GetTigerStatInfo(m_userInfo.UserId, UpdateTigerStatUI); * } * else * { * UpdateUI(); * } * } * break;*/ case DialogBtn.UpAvatar: { //DebugConsole.Log("Upload..."); DialogSelectAvatar.Show(UpdateAvatar); } break; case DialogBtn.AddFriend: { DialogBase.Show("FRIEND REQUEST", "Request to add Friend?", AddFriend); } break; case DialogBtn.RemoveFriend: { DialogBase.Show("FRIEND REMOVE", "Are you sure to remove?", RemoveFriend); } break; case DialogBtn.RegEmail: { DialogRegEmail.Show(); } break; case DialogBtn.ModifyPassword: { DialogModifyPass.Show(); } break; default: break; } }
void OnMouseDown() { DebugConsole.Log("Mouse Down"); screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)); }
protected override void Update() { base.Update(); // ESC if (Input.GetKeyDown(KeyCode.Escape)) { Debug.Log("press key ESC : Application Quit"); DebugConsole.Log("press key ESC : Application Quit"); if (Application.platform != RuntimePlatform.WindowsEditor) { // アプリケーション終了 Application.Quit(); } } // D if (Input.GetKeyDown(KeyCode.D)) { Debug.Log("press key D : Visible Debug View"); DebugConsole.Log("press key D : Visible Debug View"); // デバッグ表示のトグル DebugManager debugManager = AppMain.Instance.debugManager; debugManager.IsDebug = !debugManager.IsDebug; debugManager.ToggleShowDebugView(); } // C if (Input.GetKeyDown(KeyCode.C)) { Debug.Log("press key C : Clear DebugConsole"); DebugConsole.Log("press key C : Clear DebugConsole"); // デバッグコンソールのクリア DebugConsole.Clear(); } // W if (Input.GetKeyDown(KeyCode.W)) { Debug.Log("press key W : Change DebugConsole Mode"); DebugConsole.Log("press key W : Change DebugConsole Mode"); // デバッグコンソールのモードを切り替える if (DebugConsole.IsOpen) { if (DebugConsole.Instance.mode == DebugConsole.Mode.Log) { DebugConsole.Instance.mode = DebugConsole.Mode.WatchVars; } else { DebugConsole.Instance.mode = DebugConsole.Mode.Log; } } } // G if (Input.GetKeyDown(KeyCode.G)) { Debug.Log("press key G : System GC Collect"); DebugConsole.Log("press key G : System GC Collect"); // 強制CG System.GC.Collect(); } // R if (Input.GetKeyDown(KeyCode.R)) { Debug.Log("press key R : Reload ApplicationSetting"); DebugConsole.Log("press key R : Reload ApplicationSetting"); // 設定ファイルの再読み込み ApplicationSetting.Instance.LoadXML(); } // Space if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("press key Space : Change Stage"); DebugConsole.Log("press key Space : Change Stage"); // ステージの変更 SceneStateManager sceneStateManager = AppMain.Instance.sceneStateManager; TimeManager timeManager = AppMain.Instance.timeManager; if (sceneStateManager.CurrentState == SceneStateManager.SceneState.STARTUP) { sceneStateManager.ChangeState(SceneStateManager.SceneState.WAIT); } else if (sceneStateManager.CurrentState == SceneStateManager.SceneState.WAIT) { sceneStateManager.ChangeState(SceneStateManager.SceneState.PLAY); } else if (sceneStateManager.CurrentState == SceneStateManager.SceneState.PLAY) { timeManager.timerEvents[0].StartTimer(ApplicationSetting.Instance.GetInt("GameTime")); } else if (sceneStateManager.CurrentState == SceneStateManager.SceneState.RESULT) { sceneStateManager.ChangeAsyncState(SceneStateManager.SceneState.WAIT); } } }
private static void UpdateServerQuery(ServerList.Request query, Action <Networking.ServerInfo> onServerFound, Action <Networking.ServerInfo> onServerRulesReceived, bool includeUnresponsive) { IEnumerable <ServerList.Server> servers = includeUnresponsive ? new List <ServerList.Server>(query.Responded).Concat(query.Unresponsive) : query.Responded; foreach (ServerList.Server s in servers) { if (!ValidateServerInfo(s)) { continue; } bool responded = query.Responded.Contains(s); if (responded) { DebugConsole.Log(s.Name + " responded to server query."); } else { DebugConsole.Log(s.Name + " did not respond to server query."); } var serverInfo = new ServerInfo() { ServerName = s.Name, Port = s.ConnectionPort.ToString(), IP = s.Address.ToString(), PlayerCount = s.Players, MaxPlayers = s.MaxPlayers, HasPassword = s.Passworded, RespondedToSteamQuery = responded }; serverInfo.PingChecked = true; serverInfo.Ping = s.Ping; if (responded) { s.FetchRules(); } s.OnReceivedRules += (bool rulesReceived) => { if (!rulesReceived || s.Rules == null) { return; } if (s.Rules.ContainsKey("message")) { serverInfo.ServerMessage = s.Rules["message"]; } if (s.Rules.ContainsKey("version")) { serverInfo.GameVersion = s.Rules["version"]; } if (s.Rules.ContainsKey("playercount")) { if (int.TryParse(s.Rules["playercount"], out int playerCount)) { serverInfo.PlayerCount = playerCount; } } if (s.Rules.ContainsKey("contentpackage")) { serverInfo.ContentPackageNames.AddRange(s.Rules["contentpackage"].Split(',')); } if (s.Rules.ContainsKey("contentpackagehash")) { serverInfo.ContentPackageHashes.AddRange(s.Rules["contentpackagehash"].Split(',')); } if (s.Rules.ContainsKey("contentpackageurl")) { serverInfo.ContentPackageWorkshopUrls.AddRange(s.Rules["contentpackageurl"].Split(',')); } if (s.Rules.ContainsKey("usingwhitelist")) { serverInfo.UsingWhiteList = s.Rules["usingwhitelist"] == "True"; } if (s.Rules.ContainsKey("modeselectionmode")) { if (Enum.TryParse(s.Rules["modeselectionmode"], out SelectionMode selectionMode)) { serverInfo.ModeSelectionMode = selectionMode; } } if (s.Rules.ContainsKey("subselectionmode")) { if (Enum.TryParse(s.Rules["subselectionmode"], out SelectionMode selectionMode)) { serverInfo.SubSelectionMode = selectionMode; } } if (s.Rules.ContainsKey("allowspectating")) { serverInfo.AllowSpectating = s.Rules["allowspectating"] == "True"; } if (s.Rules.ContainsKey("allowrespawn")) { serverInfo.AllowRespawn = s.Rules["allowrespawn"] == "True"; } if (s.Rules.ContainsKey("voicechatenabled")) { serverInfo.VoipEnabled = s.Rules["voicechatenabled"] == "True"; } if (s.Rules.ContainsKey("traitors")) { if (Enum.TryParse(s.Rules["traitors"], out YesNoMaybe traitorsEnabled)) { serverInfo.TraitorsEnabled = traitorsEnabled; } } if (s.Rules.ContainsKey("gamestarted")) { serverInfo.GameStarted = s.Rules["gamestarted"] == "True"; } if (serverInfo.ContentPackageNames.Count != serverInfo.ContentPackageHashes.Count || serverInfo.ContentPackageHashes.Count != serverInfo.ContentPackageWorkshopUrls.Count) { //invalid contentpackage info serverInfo.ContentPackageNames.Clear(); serverInfo.ContentPackageHashes.Clear(); } onServerRulesReceived(serverInfo); }; onServerFound(serverInfo); } query.Responded.Clear(); }
void InitializeIpEntry() { DebugConsole.Log("getting ip via touchscreen keyboard"); keyboard = TouchScreenKeyboard.Open(IP, TouchScreenKeyboardType.NumbersAndPunctuation); }
public void OnFailedToConnect() { DebugConsole.Log("Failed to connect... trying again"); InitializeIpEntry(); //try to reconnect, this will allow you do launch the client befoer you launch the server among other things }
public void SendObject(string aObject) { mView.RPC("RecieveObject", RPCMode.Others, new object[] { aObject }); DebugConsole.Log("send:" + aObject); }
void RecieveNetworkMessage(string aMsg) { DebugConsole.Log(aMsg); }
//this is called on the CLIENT when it succesfully connects to the server public void OnDisconnectedFromServer(NetworkDisconnection info) { Connected = false; DebugConsole.Log("Disconnected from server"); InitializeIpEntry(); //try to reconnect }
private void OnLog(string info) { DebugConsole.Log(info); }
void ClientConnectWindow( int windowID ) { //GUILayout.BeginArea( new Rect(150,0,350,250) ); if (GUILayout.Button("Refresh Host List")) { MasterServer.ClearHostList(); MasterServer.RequestHostList(NetworkServer.SERVER_GAMETYPENAME); } HostData[] data = MasterServer.PollHostList(); // Go through all the hosts in the host list foreach (HostData element in data) { GUILayout.BeginHorizontal(); string name = element.gameName + " " + element.connectedPlayers + " / " + element.playerLimit; GUILayout.Label(name); GUILayout.Space(5); string hostInfo; hostInfo = "["; foreach (string host in element.ip) hostInfo = hostInfo + host + ":" + element.port + " "; hostInfo = hostInfo + "]"; GUILayout.Label(hostInfo); GUILayout.Space(5); GUILayout.Label(element.comment); GUILayout.Space(5); GUILayout.FlexibleSpace(); if (GUILayout.Button("Connect")) { // Connect to HostData struct, internally the correct method is used (GUID when using NAT). DebugConsole.Log("Connecting..." + hostInfo); NetworkConnectionError error = Network.Connect(element); if (error != NetworkConnectionError.NoError) { DebugConsole.LogError("Failed to connect " + error); } else { DebugConsole.Log("network: " + Network.peerType); } } if (GUILayout.Button("Disconnect")) { // Connect to HostData struct, internally the correct method is used (GUID when using NAT). Network.Disconnect(); DebugConsole.Log("network: " + Network.peerType); } GUILayout.EndHorizontal(); } if (GUILayout.Button("Send \"Hello World\"")) { //DebugConsole.Log("Views - "); //NetworkView[] networkViews = (NetworkView[])GetComponents(typeof(NetworkView)); //foreach (NetworkView view in networkViews) // DebugConsole.Log("- " + view.viewID); DebugConsole.Log("GOO "); if( networkView == null ) { DebugConsole.Log("networkView == null"); } else { DebugConsole.Log("networkView != null" + networkView); DebugConsole.Log( "Sending messages." ); DebugConsole.Log("networkView.viewID != null" + networkView.viewID); networkView.RPC("RPCTest", RPCMode.All, networkView.viewID, "Hello world"); //SendServerMess( MessType_ToServer.Join, null );//0 //SendServerMess( MessType_ToServer.Join, "one two" );//1 //SendServerMess( MessType_ToServer.Join, "one", "two" );//2 } if( target.networkView != null ) { DebugConsole.Log("target.networkView != null"); //target.networkView.RPC("RPCTest", RPCMode.All, target.networkView.viewID, "Hello world"); } else DebugConsole.Log("target.networkView == null"+target.networkView); } //GUILayout.EndArea(); }
private void HandleLog(string logString, string stackTrace, LogType type) { DebugConsole.Log("[" + type.ToString() + "]" + logString); }
public void SendAllSpawnBox( Vector3 location, NetworkViewID nvid ) { DebugConsole.Log("SendAllSpawnBox called with viewID: " + nvid); networkView.RPC("SpawnBox", RPCMode.AllBuffered, nvid, location ); DebugConsole.Log("SendAllSpawnBox done"); }
void OnMouseExit() { DebugConsole.Log("Mouse Exit"); }
public void SendAllScoreSync(Vector3 location, NetworkViewID nvid) { DebugConsole.Log("SendAllScoreSync called with viewID: " + nvid); networkView.RPC("ScoreSync", RPCMode.AllBuffered, nvid, location); DebugConsole.Log("SendAllScoreSync done"); }
//returns doneTesting public static bool TestConnection(int port, bool forceTest) { // Start/Poll the connection test, report the results in a label and // react to the results accordingly //Network.connectionTesterPort = port; connectionTestResult = Network.TestConnection(forceTest); switch (connectionTestResult) { case ConnectionTesterStatus.Error: testMessage = "Problem determining NAT capabilities"; doneTesting = true; break; case ConnectionTesterStatus.Undetermined: testMessage = "Undetermined NAT capabilities"; doneTesting = false; break; case ConnectionTesterStatus.PublicIPIsConnectable: testMessage = "Directly connectable public IP address."; useNat = false; doneTesting = true; break; // This case is a bit special as we now need to check if we can // circumvent the blocking by using NAT punchthrough case ConnectionTesterStatus.PublicIPPortBlocked: testMessage = "Non-connectable public IP address (port " + port + " blocked), running a server is impossible."; useNat = false; // If no NAT punchthrough test has been performed on this public // IP, force a test if (!probingPublicIP) { connectionTestResult = Network.TestConnectionNAT(); probingPublicIP = true; testStatus = "Testing if blocked public IP can be circumvented"; timer = Time.time + 10; } // NAT punchthrough test was performed but we still get blocked else if (Time.time > timer) { probingPublicIP = false; // reset useNat = true; doneTesting = true; } break; case ConnectionTesterStatus.PublicIPNoServerStarted: testMessage = "Public IP address but server not initialized, " + "it must be started to check server accessibility. Restart " + "connection test when ready (not necc.)."; doneTesting = true; break; case ConnectionTesterStatus.LimitedNATPunchthroughPortRestricted: testMessage = "Limited NAT punchthrough capabilities. Cannot " + "connect to all types of NAT servers. Running a server " + "is ill advised as not everyone can connect."; useNat = true; doneTesting = true; break; case ConnectionTesterStatus.LimitedNATPunchthroughSymmetric: testMessage = "Limited NAT punchthrough capabilities. Cannot " + "connect to all types of NAT servers. Running a server " + "is ill advised as not everyone can connect."; useNat = true; doneTesting = true; break; case ConnectionTesterStatus.NATpunchthroughAddressRestrictedCone: case ConnectionTesterStatus.NATpunchthroughFullCone: testMessage = "NAT punchthrough capable. Can connect to all " + "servers and receive connections from all clients. Enabling " + "NAT punchthrough functionality."; useNat = true; doneTesting = true; break; default: testMessage = "Error in test routine, got " + connectionTestResult; break; } if (doneTesting) { DebugConsole.Log("Connection Test done."); if (useNat) { shouldEnableNatMessage = "When starting a server the NAT " + "punchthrough feature should be enabled (useNat parameter)"; } else { shouldEnableNatMessage = "NAT punchthrough not needed"; } testStatus = "Done testing"; } return(doneTesting); }
void OnMouseDrag() { if (!enabled) { return; } dragging = true; Vector3 mousePos = invertMouse ? Input.mousePosition * -1 : Input.mousePosition; //Debug.Log ("New y: "+newY+" New x: "+newX+" New z:"+ne if (applyAsRotation) { //float center = XtopLimit - XbottomLimit; float myDir = 0; Vector3 direction; if (dragOnYAxis) { if (mousePos.y > rotateCenter) { myDir = -1; } else { myDir = 1; } } if (dragOnXAxis) { if (mousePos.x > rotateCenter) { myDir = -1; } else { myDir = 1; } } if (dragOnZAxis) { if (mousePos.z > rotateCenter) { myDir = -1; } else { myDir = 1; } } // DebugConsole.Log("Pos: "+mousePos); direction = new Vector3(applyRotationToX?myDir:0, applyRotationToY?myDir:0, applyRotationToZ?myDir:0); //Debug.Log ("Direction: "+direction); transform.RotateAround(hingePivot.transform.position, direction, Time.deltaTime * sensitivity); } else { Ray ray = dragCamera.ScreenPointToRay(mousePos * sensitivity); float dist; plane.Raycast(ray, out dist); Vector3 v3Pos = ray.GetPoint(dist); float newY = v3Pos.y + v3Offset.y; float newX = v3Pos.x + v3Offset.x; float newZ = v3Pos.z + v3Offset.z; newX = v3Pos.x + v3Offset.x; newY = v3Pos.y + v3Offset.y; newZ = v3Pos.z + v3Offset.z; Vector3 newV = transform.position; //Vector3 newRCV = dragCamera.transform.position; if (dragOnXAxis) { if (newX > XbottomLimit && newX < XtopLimit) { newV.x = newX; } } if (dragOnYAxis) { if (newY > YbottomLimit && newY < YtopLimit) { newV.y = newY; } } if (dragOnZAxis) { if (newZ > ZbottomLimit && newZ < ZtopLimit) { newV.z = newZ; } } DebugConsole.Log("New V: " + newV); transform.position = newV; } }
void OnClick(GameObject sender) { Tools.PlayAudio(Constants.Audio.Audio_LobbyClickButton); int btnIndex = GetBtnIndexFromName(sender.name); if (btnIndex < 0) { DebugConsole.Log("Cant find button:" + sender.name); return; } switch ((Constants.LobbyBtn)btnIndex) { case Constants.LobbyBtn.Btn_Slot: { // 检查是否登录 if (m_login) { Redirect(); } else { WorkDone callBack = new WorkDone(Redirect); QuickLogin(callBack); } } break; case Constants.LobbyBtn.Btn_Poker: { //DialogBase.Show("POKER", "Exit game?", QuitGame); } break; case Constants.LobbyBtn.Btn_Option: { DialogOption.Show(); } break; case Constants.LobbyBtn.Btn_Avatar: case Constants.LobbyBtn.Btn_Head: { GetProfile(Lobby.getInstance().UId, ShowPersonalInfoDlg); } break; case Constants.LobbyBtn.Btn_Message: { DialogMessage.Show(); } break; case Constants.LobbyBtn.Btn_Credits: { DialogStore.Show(0); } break; case Constants.LobbyBtn.Btn_Gems: { DialogStore.Show(1); } break; case Constants.LobbyBtn.Btn_Friends: { // 根据ActivePage获取数据 GetFriends(); } break; case Constants.LobbyBtn.Btn_FreeBonus: { TakeFreeBonus(); } break; case Constants.LobbyBtn.Btn_Bag: // Bag { GetItems(); } break; case Constants.LobbyBtn.Btn_Bingo: { //DoBuy("jb_1"); } break; case Constants.LobbyBtn.Btn_Sj: { //string uuid = GetUUID(); //DialogBase.Show("UUID", uuid); } break; default: DialogBase.Show("Button clicked", sender.name); break; } }
private void LogToConsole(string msg) { DebugConsole.Log(msg); }
// Update is called once per frame void Update() { if (Input.GetKeyUp(KeyCode.Escape)) { if (DialogBase.Actived()) { DebugConsole.Log("Hide"); DialogBase.Hide(); } else { DebugConsole.Log("Show"); DialogBase.Show("ESC", "Are you sure to exit game?", QuitGame); } } if (m_broadcastMsg != "") { // 有系统消息,平移吧 GameObject goBroadcast = GameObject.Find("BroadcastText"); Vector3 pos = goBroadcast.transform.localPosition; pos.x -= 50 * Time.deltaTime; goBroadcast.transform.localPosition = pos; // 从600~-600 if (goBroadcast.transform.localPosition.x < -600) { m_broadcastMsg = ""; } } else { m_broadcastMsg = Lobby.getInstance().GetBroadcast(); if (m_broadcastMsg != "") { GameObject goBroadcast = GameObject.Find("BroadcastText"); goBroadcast.GetComponent <Text>().text = m_broadcastMsg; goBroadcast.transform.localPosition = new Vector3(600, 0, 0); } } if (m_net == null || !m_net.IsRunning()) { // 主动结束了 return; } if (m_net.CheckReconnect()) { CheckLogin(); DialogReconnect.Hide(); } ProtoPacket packet = new ProtoPacket(); if (m_net.RecvTryDequeue(ref packet)) { DebugConsole.Log("Reception handle cmdId:" + packet.cmdId); switch (packet.cmdId) { case Constants.Lion_QuickLoginInfo: { Lobby.getInstance().UserInfo = (LionUserInfo)packet.proto; // 更新LionUser m_login = true; UpdateUserInfoUI(); // 更新大厅主界面中信息 if (packet.callback != null) { packet.callback(); } } break; case Constants.Lion_GetProfile: { LionUserInfo usrInfo = (LionUserInfo)packet.proto; // 更新LionUser if (usrInfo.UserId == Lobby.getInstance().UId) { Lobby.getInstance().UserInfo = usrInfo; } Lobby.getInstance().QueryUserInfo = usrInfo; if (packet.callback != null) { // 通常这里显示个人信息对话框 packet.callback(); } } break; case Constants.Lion_GetTigerStat: { Lobby.getInstance().TigerStatInfo = (TigerStat)packet.proto; if (packet.callback != null) { packet.callback(); } } break; case Constants.Lion_GetFriendRequests: case Constants.Lion_GetFriends: { Lobby.getInstance().FriendIDArray = (LongArray)packet.proto; if (packet.callback != null) { GetFriendSummary(packet.callback); } else { GetFriendSummary(ShowFriendsDlg); } } break; case Constants.Lion_GetFriendSummary: { Lobby.getInstance().CurrentSummaryList = (FriendSummaryList)packet.proto; DebugConsole.Log("Summary count:" + Lobby.getInstance().CurrentSummaryList.Data.Count); if (packet.callback != null) { packet.callback(); } } break; case Constants.Lion_IgnoreFriend: case Constants.Lion_AcceptFriend: case Constants.Lion_AddFriend: case Constants.Lion_DeleteFriend: { Status stat = (Status)packet.proto; if (stat.Code == 0) // successful { if (packet.callback != null) { packet.callback(); } } else { DebugConsole.Log(stat.Desc); } } break; case Constants.Lion_Redirect: { Lobby.getInstance().RedirectInfo = (RedirectResp)packet.proto; // 切换到游戏场景中 //m_net.Close(); DebugConsole.Log("Reception enter slot scene"); Global.NextSceneName = "slot"; SceneManager.LoadScene("loading"); } break; case Constants.Lion_UpdateProfile: { DebugConsole.Log("Lion_UpdateProfile"); Status stat = (Status)packet.proto; if (stat.Code == 0) // successful { if (packet.callback != null) { packet.callback(); } } else { DebugConsole.Log(stat.Desc); } } break; case Constants.Lion_NotifyWeeklyLogin: { // 连续登录奖励 // NotifyWeeklyLogin 返回的intvalue是0-6,0表示今天登陆了(昨天没登录) IntValue iv = (IntValue)packet.proto; DialogDailyBonus.Show(iv.Value); //ExplodeCoin.Show(); } break; case Constants.Lion_TakeLoginBonus: { LongArray la = (LongArray)packet.proto; // la[0] 奖励金币数 // la[1] 最终总数 if (la.Data.Count >= 2) { Lobby.getInstance().UserInfo.Gold = la.Data[1]; // 若有动画,在此添加 JumpAndMoveCoins(6, UpdateUserInfoUI); } } break; case Constants.Lion_NotifyFreeBonus: { // 第一次登陆的时候,数据库里面没有数据,所以返回0 // 后端推送,倒计时剩余时间长度(毫秒),如果小于等于0,直接显示奖励 // 免费奖励 LongValue lv = (LongValue)packet.proto; long curEpoch = (System.DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000; Lobby.getInstance().FreeBonusEpoch = curEpoch + lv.Value; UpdateCountDown(); } break; case Constants.Lion_TakeFreeBonus: { LongArray la = (LongArray)packet.proto; if (la.Data.Count >= 2) { Lobby.getInstance().UserInfo.Gold = la.Data[1]; // 若有动画,在此添加 FlyCoin(Constants.Bonus_Free); UpdateUserInfoUI(); } } break; case Constants.Lion_BuyItem: { Status stat = (Status)packet.proto; // 更新购买相关的:金币 or 背包 DebugConsole.Log("Buy item return:" + stat.Code.ToString()); if (stat.Code == 0) // successful { if (packet.callback != null) { packet.callback(); } } else { DebugConsole.Log(stat.Desc); } } break; case Constants.Lion_Register: { Status stat = (Status)packet.proto; DebugConsole.Log("Register by email return:" + stat.Code.ToString()); if (stat.Code == 0) // successful { if (packet.callback != null) { packet.callback(); } } else { DebugConsole.Log(stat.Desc); DialogBase.Show("Register by email", "Error:" + stat.Desc); } } break; case Constants.Lion_ModPass: { Status stat = (Status)packet.proto; DebugConsole.Log("Modify password return:" + stat.Code.ToString()); if (stat.Code == 0) // successful { if (packet.callback != null) { packet.callback(); } } else { DebugConsole.Log(stat.Desc); DialogBase.Show("Modify password", "Error:" + stat.Desc); } } break; case Constants.Lion_RefreshGold: { LongValue lv = (LongValue)packet.proto; DebugConsole.Log("Refresh gold:" + lv.ToString()); Lobby.getInstance().UserInfo.Gold = lv.Value; UpdateUserInfoUI(); } break; case Constants.Lion_GetShopItems: { Lobby.getInstance().ShopList = (ShopList)packet.proto; DebugConsole.Log("ShopName:" + Lobby.getInstance().ShopList.ShopName); if (packet.callback != null) { packet.callback(); } } break; case Constants.Lion_BroadcastSystemMessage: { Tools.PlayNotification(Constants.Audio.Audio_Notification); StringValue sv = (StringValue)packet.proto; Lobby.getInstance().AddBroadcast(sv.Value); } break; case Constants.Lion_GetItems: { // Lobby.getInstance().UserItemList = (UserItemList)packet.proto; if (packet.callback != null) { packet.callback(); } else { DialogBag.Show(null); } } break; case Constants.Reconnect: { // 展示重连对话框,直到重连成功 if (packet.msgId == 1) { ProtoNet.WriteLog("Reconnecting..."); // 3s后Display中重连 m_net.CheckReconnect(3); DialogReconnect.Show(); } } break; case Constants.Error: { // 展示错误 Status stat = (Status)packet.proto; string err = "Error:" + stat.Code.ToString() + "-" + stat.Desc; DialogBase.Show("ERROR", err); } break; default: { DebugConsole.Log("Reception invalid cmdId:" + packet.cmdId); } break; } } }
public void ReadMessage(IReadMessage inc) { System.Diagnostics.Debug.Assert(!activeTransfers.Any(t => t.Status == FileTransferStatus.Error || t.Status == FileTransferStatus.Canceled || t.Status == FileTransferStatus.Finished), "List of active file transfers contains entires that should have been removed"); byte transferMessageType = inc.ReadByte(); switch (transferMessageType) { case (byte)FileTransferMessageType.Initiate: { byte transferId = inc.ReadByte(); var existingTransfer = activeTransfers.Find(t => t.ID == transferId); finishedTransfers.RemoveAll(t => t.First == transferId); byte fileType = inc.ReadByte(); //ushort chunkLen = inc.ReadUInt16(); int fileSize = inc.ReadInt32(); string fileName = inc.ReadString(); if (existingTransfer != null) { if (fileType != (byte)existingTransfer.FileType || fileSize != existingTransfer.FileSize || fileName != existingTransfer.FileName) { GameMain.Client.CancelFileTransfer(transferId); DebugConsole.ThrowError("File transfer error: file transfer initiated with an ID that's already in use"); } else //resend acknowledgement packet { GameMain.Client.UpdateFileTransfer(transferId, 0); } return; } if (!ValidateInitialData(fileType, fileName, fileSize, out string errorMsg)) { GameMain.Client.CancelFileTransfer(transferId); DebugConsole.ThrowError("File transfer failed (" + errorMsg + ")"); return; } if (GameSettings.VerboseLogging) { DebugConsole.Log("Received file transfer initiation message: "); DebugConsole.Log(" File: " + fileName); DebugConsole.Log(" Size: " + fileSize); DebugConsole.Log(" ID: " + transferId); } string downloadFolder = downloadFolders[(FileTransferType)fileType]; if (!Directory.Exists(downloadFolder)) { try { Directory.CreateDirectory(downloadFolder); } catch (Exception e) { DebugConsole.ThrowError("Could not start a file transfer: failed to create the folder \"" + downloadFolder + "\".", e); return; } } FileTransferIn newTransfer = new FileTransferIn(inc.Sender, Path.Combine(downloadFolder, fileName), (FileTransferType)fileType) { ID = transferId, Status = FileTransferStatus.Receiving, FileSize = fileSize }; int maxRetries = 4; for (int i = 0; i <= maxRetries; i++) { try { newTransfer.OpenStream(); } catch (System.IO.IOException e) { if (i < maxRetries) { DebugConsole.NewMessage("Failed to initiate a file transfer {" + e.Message + "}, retrying in 250 ms...", Color.Red); Thread.Sleep(250); } else { DebugConsole.NewMessage("Failed to initiate a file transfer {" + e.Message + "}", Color.Red); GameMain.Client.CancelFileTransfer(transferId); newTransfer.Status = FileTransferStatus.Error; OnTransferFailed(newTransfer); return; } } } activeTransfers.Add(newTransfer); GameMain.Client.UpdateFileTransfer(transferId, 0); //send acknowledgement packet } break; case (byte)FileTransferMessageType.TransferOnSameMachine: { byte transferId = inc.ReadByte(); byte fileType = inc.ReadByte(); string filePath = inc.ReadString(); if (GameSettings.VerboseLogging) { DebugConsole.Log("Received file transfer message on the same machine: "); DebugConsole.Log(" File: " + filePath); DebugConsole.Log(" ID: " + transferId); } if (!File.Exists(filePath)) { DebugConsole.ThrowError("File transfer on the same machine failed, file \"" + filePath + "\" not found."); GameMain.Client.CancelFileTransfer(transferId); return; } FileTransferIn directTransfer = new FileTransferIn(inc.Sender, filePath, (FileTransferType)fileType) { ID = transferId, Status = FileTransferStatus.Finished, FileSize = 0 }; Md5Hash.RemoveFromCache(directTransfer.FilePath); OnFinished(directTransfer); } break; case (byte)FileTransferMessageType.Data: { byte transferId = inc.ReadByte(); var activeTransfer = activeTransfers.Find(t => t.Connection == inc.Sender && t.ID == transferId); if (activeTransfer == null) { //it's possible for the server to send some extra data //before it acknowledges that the download is finished, //so let's suppress the error message in that case finishedTransfers.RemoveAll(t => t.Second + 5.0 < Timing.TotalTime); if (!finishedTransfers.Any(t => t.First == transferId)) { GameMain.Client.CancelFileTransfer(transferId); DebugConsole.ThrowError("File transfer error: received data without a transfer initiation message"); } return; } int offset = inc.ReadInt32(); if (offset != activeTransfer.Received) { if (offset < activeTransfer.Received) { GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received); } return; } int bytesToRead = inc.ReadUInt16(); if (activeTransfer.Received + bytesToRead > activeTransfer.FileSize) { GameMain.Client.CancelFileTransfer(transferId); DebugConsole.ThrowError("File transfer error: Received more data than expected (total received: " + activeTransfer.Received + ", msg received: " + (inc.LengthBytes - inc.BytePosition) + ", msg length: " + inc.LengthBytes + ", msg read: " + inc.BytePosition + ", filesize: " + activeTransfer.FileSize); activeTransfer.Status = FileTransferStatus.Error; StopTransfer(activeTransfer); return; } try { activeTransfer.ReadBytes(inc, bytesToRead); } catch (Exception e) { GameMain.Client.CancelFileTransfer(transferId); DebugConsole.ThrowError("File transfer error: " + e.Message); activeTransfer.Status = FileTransferStatus.Error; StopTransfer(activeTransfer, true); return; } if (activeTransfer.Status == FileTransferStatus.Finished) { GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received, true); activeTransfer.Dispose(); if (ValidateReceivedData(activeTransfer, out string errorMessage)) { finishedTransfers.Add(new Pair <int, double>(transferId, Timing.TotalTime)); StopTransfer(activeTransfer); Md5Hash.RemoveFromCache(activeTransfer.FilePath); OnFinished(activeTransfer); } else { new GUIMessageBox("File transfer aborted", errorMessage); activeTransfer.Status = FileTransferStatus.Error; StopTransfer(activeTransfer, true); } } } break; case (byte)FileTransferMessageType.Cancel: { byte transferId = inc.ReadByte(); var matchingTransfer = activeTransfers.Find(t => t.Connection == inc.Sender && t.ID == transferId); if (matchingTransfer != null) { new GUIMessageBox("File transfer cancelled", "The server has cancelled the transfer of the file \"" + matchingTransfer.FileName + "\"."); StopTransfer(matchingTransfer); } break; } } }
/// <summary> /// Save string in the database /// </summary> /// <param name="dbstr"></param> public void SaveToDB(string dbstr) { DebugConsole.Log("[DBClientProxy]:SaveToDB - saving to db the string: " + dbstr); NetworkClient.Instance.SendServerMess(NetworkClient.MessType_ToServer.SaveDBStr, dbstr); }
void toggleCollumation(bool coll) { DebugConsole.Log("Collumation clicked" + coll); CollumationController.collOn = coll; collumation.SetActive(coll); }
private void ReadClientSteamAuthRequest(NetIncomingMessage inc, NetConnection senderConnection, out ulong clientSteamID) { clientSteamID = 0; if (!Steam.SteamManager.USE_STEAM) { DebugConsole.Log("Received a Steam auth request from " + senderConnection.RemoteEndPoint + ". Steam authentication not required, handling auth normally."); //not using steam, handle auth normally HandleClientAuthRequest(senderConnection, 0); return; } if (senderConnection == OwnerConnection) { //the client is the owner of the server, no need for authentication //(it would fail with a "duplicate request" error anyway) HandleClientAuthRequest(senderConnection, 0); return; } clientSteamID = inc.ReadUInt64(); int authTicketLength = inc.ReadInt32(); inc.ReadBytes(authTicketLength, out byte[] authTicketData); DebugConsole.Log("Received a Steam auth request"); DebugConsole.Log(" Steam ID: " + clientSteamID); DebugConsole.Log(" Auth ticket length: " + authTicketLength); DebugConsole.Log(" Auth ticket data: " + ((authTicketData == null) ? "null" : ToolBox.LimitString(string.Concat(authTicketData.Select(b => b.ToString("X2"))), 16))); if (senderConnection != OwnerConnection && serverSettings.BanList.IsBanned(senderConnection.RemoteEndPoint.Address, clientSteamID)) { return; } ulong steamID = clientSteamID; if (unauthenticatedClients.Any(uc => uc.Connection == inc.SenderConnection)) { var steamAuthedClient = unauthenticatedClients.Find(uc => uc.Connection == inc.SenderConnection && uc.SteamID == steamID && uc.SteamAuthStatus == Facepunch.Steamworks.ServerAuth.Status.OK); if (steamAuthedClient != null) { DebugConsole.Log("Client already authenticated, sending AUTH_RESPONSE again..."); HandleClientAuthRequest(inc.SenderConnection, steamID); } DebugConsole.Log("Steam authentication already pending..."); return; } if (authTicketData == null) { DebugConsole.Log("Invalid request"); return; } unauthenticatedClients.RemoveAll(uc => uc.Connection == senderConnection); int nonce = CryptoRandom.Instance.Next(); var unauthClient = new UnauthenticatedClient(senderConnection, nonce, clientSteamID) { AuthTimer = 20 }; unauthenticatedClients.Add(unauthClient); if (!Steam.SteamManager.StartAuthSession(authTicketData, clientSteamID)) { unauthenticatedClients.Remove(unauthClient); if (GameMain.Config.RequireSteamAuthentication) { unauthClient.Connection.Disconnect(DisconnectReason.SteamAuthenticationFailed.ToString()); Log("Disconnected unauthenticated client (Steam ID: " + steamID + "). Steam authentication failed.", ServerLog.MessageType.ServerMessage); } else { DebugConsole.Log("Steam authentication failed, skipping to basic auth..."); HandleClientAuthRequest(senderConnection); return; } } return; }
void OnDestroy() { DebugConsole.Log("SocketClientManager destroy"); }