static void Main(string[] args) { var sport = args.Length > 0 ? args[0] : "999"; InitValueDefs.dbconnect = args.Length > 1 ? args[1] : "mongodb://127.0.0.1:27018"; InitValueDefs.dbname = args.Length > 2 ? args[2] : "common"; AOutput.bIsConsole = true; AOutput.Instance.RegistOutputDel(doLog); AOutput.LogTag = EngineServer.eServerType.ToString(); EngineServer.Instance.EngineInit(); EngineServer.Instance.ServerStartUp(typeParser.intParse(sport), EngineServer.EServerType.GatewayServer); GameHandlers_Enter.Instance.Init(); EngineServer.Instance.RegistSubSystem(GameHandlers_Enter.Instance); StartConsoleServer(); try { ConfigManager.Instance.Init(); AOutput.Log($"Config loaded."); } catch (Exception ex) { AOutput.LogError($"Load config error:{ex.Message}"); } }
private void Start() { #if UNITY_ANDROID MonoInstancePool.getInstance <SDK_Orientation>(true).ShowBar(); #endif Screen.fullScreen = true; MonoInstancePool.getInstance <AntiScriptSplit>(true); MonoInstancePool.getInstance <SDK_WeChat>(true); trUIAlert = UStaticFuncs.FindChildComponent <Transform>(transform, "UIAlert"); fprocessing = 0.1f; #if UNITY_IOS MonoInstancePool.getInstance <SDK_AppleInApp>(true); #endif gameObject.AddComponent <UConsoleDebug>(); #if !UNITY_WEBGL var fa = "fa" + Utils_Plugins.Util_GetBundleVersion(); if (!PlayerPrefs.HasKey(fa)) { AOutput.Log($"start copy files {fa}"); MonoInstancePool.getInstance <UCopyFilesFromStreamingAssets>().OnCopy("versions.txt", UStaticFuncs.ConfigSaveDir, () => { InitRemoteConfig(); PlayerPrefs.SetInt("fa" + Utils_Plugins.Util_GetBundleVersion(), 1); }); } else { #endif InitRemoteConfig(); #if !UNITY_WEBGL } #endif }
private void GameHandler_CreateOrderRequest(IResponer responer, PktCreateOrderRequest vo) { var player = APlayerManager.Instance.OnGetPlayerByConn(responer.playerConnDesc); if (player == null) { return; } var data = PaymentLoader.Instance.OnGetData(vo.productID); var result = new PktCreateOrderResult(); if (data == null) { return; } result.eResult = PktCreateOrderResult.EResult.Success; var orders = new CakeServer("order", player.psid); var order = orders.GetSingleItem(LibUtils.StringUtils.GetGUIDString()); order.SetValue(ParamNameDefs.ProductID, vo.productID); order.SetValue(ParamNameDefs.Price, data.Price); result.orderID = order.iid; result.extraInfo = APIWechatPay.Pay(data.Price, order.iid, $"描述:{data.Desc}"); AOutput.Log($"result.extraInfo {result.extraInfo}"); responer.Response(result); }
public void OnDownloadResources(List <string> lResources, Action downloaded, Action <float> progress = null) { AOutput.Log($"OnDownloadResources Environment.UseAB {Environment.UseAB} {Utils.GetPlatformFolder(Application.platform)} {string.Join(",", lResources)}"); if (!Environment.UseAB) { downloaded?.Invoke(); return; } if (dRemoteVersions.Count == 0) { OnDownloadText(Utils.GetPlatformFolder(Application.platform) + "/versions", (content) => { var acontent = content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var c in acontent) { var ac = c.Split('|'); if (ac.Length < 2) { continue; } if (!dRemoteVersions.ContainsKey(ac[0])) { dRemoteVersions.Add(ac[0], ac[1]); } } DoCheckVersions(lResources, downloaded, progress); }); } else { DoCheckVersions(lResources, downloaded, progress); } }
private void ProcessStreamData() { if (TryPraseProcessSecurityRequest()) { return; } while (0 < m_SocketData.BytesUnread) { if (!m_bValidPacketHeader) { if (!ReadPacketHeader()) { if (showInvalidSocketData) { AOutput.Log("Invalid socket data from " + ConnectionDesc + " count:" + m_SocketData.BytesUnread); } break; } } else { ReadPacketData(); } } }
public void ServerTick() { DateTime nowTime = DateTime.Now; TimeSpan span = nowTime - m_OldTime; foreach (ITickableSystem subSystem in m_vSubSystems) { m_OldTime = nowTime; DateTime ot = DateTime.Now; try { subSystem.Tick(span.TotalSeconds); } catch (Exception ex) { AOutput.Log("Tick exception " + ex.Message); AOutput.Log(ex.StackTrace); } DateTime nt = DateTime.Now; double t = (nt - ot).TotalMilliseconds; if (t > 300) { AOutput.Log(subSystem.GetType().FullName + " spans (ms)" + t); } } Thread.Sleep(1); }
private void CreatePacket() { eMessageType eOpCode = (eMessageType)m_bOpCode; ResetPacketHeader(); m_PacketDataStream.Position = 0; // reset position so it is ready for reading Packet packet = ClientConnectionUtil.ProcessClientPacket(eOpCode, m_PacketDataStream, this); if (packet != null) { m_vPacketsToProcess.Enqueue(new SinglePacketProcessor(packet)); EngineControler.Instance.QueForProcessing(this); } else { AOutput.Log("Create packet failed!"); } if (m_vSocketData.Count > 0) { EngineControler.Instance.QueForTick(this); } }
public void FactoryInit(ByteStream buffer, ClientConnection client) { m_Client = client; if (null == buffer) { return; } try { int iPacketSize = buffer.Length; Initialize(buffer); if (buffer.BytesRead != iPacketSize) { string error = string.Format(@"Packet size mismatch of type {0}", this.GetType().ToString()); AOutput.Log(error); throw new System.Exception(error); } } catch { AOutput.Log(string.Format(@"Failed Initializing Packet of type {0}", this.GetType().ToString())); m_bValid = false; } }
/// <summary> /// Processes an incoming packet to an ClientConnection interface /// </summary> /// <param name="messageType">Packet message identifier</param> /// <param name="packetStream">Packet stream data</param> /// <param name="client">Client interface to handle the packet</param> /// <param name="bThrowOnError">True to throw an exception instead of logging</param> /// <returns>Packet to process or NULL if a control packet dispatched to the client</returns> public static Packet ProcessClientPacket(eMessageType messageType, Stream packetStream, ClientConnection client, bool bThrowOnError) { // string userName = ( client.ConnectionUser != null ) ? client.ConnectionUser.Login : "******"; Packet packet = PacketFactory.Instance.ParseData(messageType, packetStream, client); // if( packet is LogoutPacket ) // { // client.SignalLogout(); // return null; // } //else if (packet.IsValid) { return(packet); } if (bThrowOnError) { throw new InvalidOperationException(string.Format(@"Invalid Packet Data Received For Type '{0}'. {1}", messageType, "userName")); } else { AOutput.Log(string.Format(@"Invalid Packet Data Received For Type '{0}'. {1}", messageType, "userName")); } return(null); }
public void OnEnter(AAvatar avatar, string roomType) { if (!avatar.bAI) { if (dRooms.ContainsKey(avatar.username)) { if (dRooms[avatar.username].roomType != roomType) { AOutput.Log($"avatar.username enter different room {roomType}"); dRooms[avatar.username].OnExit(avatar.username); dRooms.Remove(avatar.username); } } ARoomBase room = null; if (!dRooms.ContainsKey(avatar.username)) { room = OnCreate(roomType); dRooms.Add(avatar.username, room); } else { room = dRooms[avatar.username]; } room.OnEnter(avatar); } }
protected void Application_BeginRequest(object sender, EventArgs e) { string hPath = Request.Url.LocalPath.ToString().ToLower(); if (!hPath.Contains(".asmx")) { foreach (var p in ConfigurationManager.AppSettings.AllKeys) { if (!p.StartsWith("/")) { continue; } if (!hPath.Contains(p)) { continue; } Context.RewritePath(hPath.Replace(p, ConfigurationManager.AppSettings[p])); break; } //Context.RewritePath(hPath.Replace("/validate", "/Enter.asmx/validate")); } AOutput.Log(""); AOutput.Log("URL:" + Request.RawUrl); AOutput.Log("FORM:" + Request.Form.ToString()); AOutput.Log("IP:" + Request.UserHostAddress); AOutput.Log("USER:"******""); }
private async Task BeginRead() { if (!IsConnected) { return; } try { byte[] buffer = new byte[readbuffsize]; var iBytesAvailable = await m_ClientStream.ReadAsync(buffer, 0, readbuffsize); if (0 >= iBytesAvailable) { AddDisconectPacket(); return; } else { SocketData data = new SocketData(buffer, iBytesAvailable); m_vSocketData.Enqueue(data); EngineControler.Instance.QueForTick(this); } lastReceiveDataTime = ApiDateTime.Now; await BeginRead(); } catch (System.Exception ex) { AOutput.Log($"ReadComplete {ex.Message}"); AddDisconectPacket(); } }
private void InitRemoteConfig() { SetJindu("正在检查本地资源版本,请稍候"); AOutput.Log("InitRemoteConfig"); ConfigDownloader.Instance.StartToDownload(ConfigURL, () => { ParseConfigs(); if (UConfigManager.bUsingAb) { SetJindu("正在加载脚本资源......"); StartCoroutine(OnDownloadDll(ConfigDownloader.Instance.OnGetValue("dll"))); } else { SetJindu("正在加载脚本资源..."); LoadDll(File.ReadAllBytes("Assets/RemoteResources/Dll/ahotgames.bytes") , File.ReadAllBytes("Assets/RemoteResources/Dll/ahotgames.pdb")); } }, () => { SetJindu("正在加载本地资源,请稍候"); Debug.Log("下载远端配置文件失败,加载本地文件"); UConfigManager.bUsingAb = false; StartCoroutine(OnDownloadDll(UStaticFuncs.GetStreamAssetPath() + UStaticFuncs.GetPlatformFolder(Application.platform) + "/dll/ahotgames.ab")); }); }
IEnumerator OnDownloadDll(string dllPath) { AOutput.Log($"dllPath {dllPath}"); www = new WWW(dllPath); yield return(www); if (string.IsNullOrEmpty(www.error)) { if (dllPath.EndsWith(".ab")) { LoadDll(www.assetBundle.LoadAsset <TextAsset>("ahotgames").bytes, null); } else { var dllBytes = www.bytes; #if UNITY_EDITOR www = new WWW(dllPath.Replace(".bytes", ".pdb")); AOutput.Log($"www {www.url}"); yield return(www); LoadDll(dllBytes, www.bytes); #else LoadDll(dllBytes, null); #endif } } else { AOutput.Log($"www {www.url} error {www.error}"); } www = null; }
public void DownloadConfig(Action downloadConfigComplete) { var ks = dExcelLoaders.Keys.ToArray(); var l = new List <string>(); foreach (var k in ks) { l.Add($"txt/{k}"); } UHotAssetBundleLoader.Instance.OnDownloadResources(() => { foreach (var k in dExcelLoaders.Keys) { var tb = "txt/" + k; var ta = UHotAssetBundleLoader.Instance.OnLoadAsset <TextAsset>(tb); if (ta != null) { dExcelLoaders[k].Invoke(ta.text); } else { AOutput.Log($"Load config invalid {tb}"); } } downloadConfigComplete(); }, l.ToArray()); }
public void Start(int port, Action <IPEndPoint, byte[]> bytesReceiveHandler) { if (udpClient != null) { return; } udpClient = new UdpClient(port); receiveHandler = bytesReceiveHandler; ipendpoint = new IPEndPoint(IPAddress.Any, port); ipendpointv6 = new IPEndPoint(IPAddress.IPv6Any, port); var addresses = Dns.GetHostAddresses(Dns.GetHostName()); AOutput.Log("Listening UDP " + addresses.Length + " addresses"); foreach (var adr in addresses) { AOutput.Log("\t" + adr.ToString()); } if (receiveHandler != null) { new Thread(new ThreadStart(ReceiveHand)).Start(); new Thread(new ThreadStart(ReceiveHandV6)).Start(); } }
public static string CreateZip(string zipPath, string dirPath) { ZipFile czip = ZipFile.Create(zipPath); czip.Password = Pd; DiskArchiveStorage myDisk = new DiskArchiveStorage(czip); czip.BeginUpdate(myDisk); var files = Directory.EnumerateFiles(dirPath); foreach (string file in files) { if (!file.EndsWith(".txt")) { continue; } if (!File.Exists(file)) { AOutput.Log("File not found!"); } czip.Add(file, Path.GetFileName(file)); } czip.CommitUpdate(); czip.Close(); return(zipPath); }
protected override void InitComponents() { UICommonWait.Show(); Task.Run(async() => { if (!LibClient.AClientApp.bConnected) { await LibClient.AClientApp.StartClient(); } UEventListener.Instance.AddProducingAction(() => { UICommonWait.Hide(); }); }); inputUsername = FindWidget <InputField>("inputUsername"); if (!string.IsNullOrEmpty(CachedUsername)) { inputUsername.text = CachedUsername; } inputPassword = FindWidget <InputField>("inputPassword"); btnLogin = FindWidget <Button>("btnLogin"); btnLogin.onClick.AddListener(() => { Task.Run(async() => { if (!LibClient.AClientApp.bConnected) { await LibClient.AClientApp.StartClient(); } if (!LibClient.AClientApp.bConnected) { UEventListener.Instance.AddProducingAction(() => { btnLogin.enabled = true; UICommonWait.Hide(); }); AOutput.Log($"连接失败!"); return; } UEventListener.Instance.AddProducingAction(OnLogin); }); btnLogin.enabled = false; }); var btnRegister = FindWidget <Button>("btnRegister"); btnRegister.onClick.AddListener((UnityEngine.Events.UnityAction)(() => { base.OnUnloadThis(); AHotBase.LoadUI <UIRegister>(); })); RegisterEvent(UEvents.Login, OnLoginCb); }
public void ListAll() { foreach (var a in dUIDIndexedAvatars) { AOutput.Log($"[{a.Key}]{a.Value.AvatarName} Lv:{a.Value.AvatarLevel}"); } AOutput.Log($"Total:{dUIDIndexedAvatars.Count}"); }
internal override void rcvLoginCb(bool bSuccess, string uid, PktLoginRequest.EPartnerID ePartnerID) { if (bSuccess) { AClientApis.OnEnterGame(uid, ePartnerID); } AOutput.Log($"rcvLoginCb {bSuccess}, {uid}"); }
internal override void rcvItemNotify(PktItemNotify arg2) { AOutput.Log($"rcvItemNotify {arg2.lItems.Count}"); foreach (var arg in arg2.lItems) { AOutput.Log($"rcv item {arg.contentID}:{arg.num}"); } }
public override void rcvEnterGameCb(AvatarInfo info) { AOutput.Log($"rcvEnterGameCb"); UEventListener.Instance.OnDispatchEvent(UEvents.EnterGame, new EventEnterGame() { info = info }); }
private async Task ProcessChat(AspNetWebSocketContext context) { WebSocket socket = context.WebSocket; string user = ""; try { var allkeys = context.QueryString.AllKeys.ToList(); if (allkeys.Contains("username") && allkeys.Contains("token")) { user = context.QueryString["username"]; var token = context.QueryString["token"]; var check = ATokenManager.Instance.OnCheckToken(user, token); if (!check) { AOutput.Log("invalid token " + user + "/" + token); return; } #region 用户添加连接池 //第一次open时,添加到连接池中 if (!CONNECT_POOL.ContainsKey(user)) { CONNECT_POOL.Add(user, new UserWithToken() { connect = socket, username = user }); //不存在,添加 } else if (socket != CONNECT_POOL[user].connect) //当前对象不一致,更新 { CONNECT_POOL[user].DoCancelConnect(); CONNECT_POOL[user] = new UserWithToken() { connect = socket, username = user }; } #endregion await DoSend(CONNECT_POOL[user], AWebServerUtils.OnGetJsonError("0")); } else { AOutput.Log("invalid argument"); return; } await StartReceive(socket, user); } catch (Exception ex) { try { AOutput.LogError("监听异常:" + ex.Message); AOutput.LogError("异常堆栈:" + ex.StackTrace); } catch { } } }
private void OnCreateOrderCb(UEventBase obj) { var eb = obj as EventCreateOrder; AOutput.Log($"obj {eb.eResult} {eb.orderID} {eb.extraInfo}"); //AClientApis.OnPay(1); UICommonWait.Show(); OnSendSDKMessage("SDK_AppleInApp", "OnBuyProduct", "0"); }
public static string OnWebRequestGet(string url) { AOutput.Log("OnWebRequestGet " + url); var req = (HttpWebRequest)HttpWebRequest.Create(url); using (WebResponse wr = req.GetResponse()) { return(new StreamReader(wr.GetResponseStream(), Encoding.UTF8).ReadToEnd()); } }
public T FindWidgetWithPath <T>(Transform trans, string widgetName) where T : Component { var t = UStaticFuncs.FindChildComponent <T>(trans, widgetName); if (t == null) { AOutput.Log("FindWidget failed " + widgetName); } return(t); }
private WWW OnDownloadBytes(string resource , string version , Action <string> downloadedAction , Action <string> errorAction = null , Action <float> progressAction = null ) { if (!Environment.UseAB) { return(null); } var url = Utils.BaseURL_Res + Utils.GetPlatformFolder(Application.platform) + resource; var www = new WWW(url); AOutput.Log($"Downloading {url}"); addUpdateAction(() => { if (www.isDone) { progressAction?.Invoke(1); if (string.IsNullOrEmpty(www.error)) { var filepath = Utils.ConfigSaveDir + resource; var fi = new FileInfo(filepath); if (!fi.Directory.Exists) { fi.Directory.Create(); } File.WriteAllBytes(filepath, www.bytes); ULocalFileManager.Instance.OnAddFile(resource, version); downloadedAction?.Invoke(resource); } else { UDebugHotLog.Log($"{url} error {www.error}"); errorAction?.Invoke(www.error); } return(true); } else { if (progressAction != null) { progressAction(www.progress); } else { UDebugHotLog.Log($"OnDownloadBytes process {www.progress}"); UILoading.Instance?.OnSetProgress(www.progress); } } return(false); }); return(www); }
protected override void InitComponents() { UICommonWait.Show(); Task.Run(async() => { if (!LibClient.AClientApp.bConnected) { await LibClient.AClientApp.StartClient(); } UEventListener.Instance.AddProducingAction(() => { UICommonWait.Hide(); }); }); inputUsername = FindWidget <InputField>("inputUsername"); if (!string.IsNullOrEmpty(CachedUsername)) { inputUsername.text = CachedUsername; } inputPassword = FindWidget <InputField>("inputPassword"); btnLogin = FindWidget <Button>("btnLogin"); btnLogin.onClick.AddListener(() => { Task.Run(async() => { if (!LibClient.AClientApp.bConnected) { await LibClient.AClientApp.StartClient(); } if (!LibClient.AClientApp.bConnected) { AOutput.Log($"连接失败!"); return; } UEventListener.Instance.AddProducingAction(OnLogin); }); btnLogin.enabled = false; }); var btnRegister = FindWidget <Button>("btnRegister"); btnRegister.onClick.AddListener(() => { OnUnloadThis(); LoadAnotherUI <UIRegister>(); }); UEventListener.Instance.OnRegisterEvent(UEvents.LoginFailed, OnLoginFailedCb); UEventListener.Instance.OnRegisterEvent(UEvents.EnterGame, OnEnterGameCb); UEventListener.Instance.OnRegisterEvent(UEvents.ServerDisconnected, OnServerDisconnectedCb); }
internal void OnOffline(string username) { AOutput.Log($"OnOffline {username}"); if (!dRooms.ContainsKey(username)) { return; } var room = dRooms[username]; room.OnOffline(username); }
public void DoWork(object o) { try { m_finished.Finished(); } catch (Exception ex) { AOutput.Log(ex.StackTrace); } }