public async Task <bool> Process(HttpContext context, ResponseHandle resp) { ESBContext esbContext = new ESBContext(); var headers = context.Request.Headers.GetEnumerator(); esbContext.Headers = new Dictionary <string, string>(); if (context.Request.Headers != null) { while (headers.MoveNext()) { esbContext.Headers.Add(headers.Current.Key, headers.Current.Value); } } await ReadBody(context, esbContext); esbContext.Host = context.Request.Host.Value; ExtractIP(context, esbContext); esbContext.Method = context.Request.Method; esbContext.Path = context.Request.Path; esbContext.QueryString = context.Request.QueryString.Value; esbContext.Url = string.Format("{0}://{1}{2}{3}", context.Request.Scheme, context.Request.Host, context.Request.Path, context.Request.QueryString); return(await process.Process(esbContext, resp)); }
private void ConsumeResources(ResponseHandle <Resources.Commands.ConsumeResources, ConsumptionRequest, ConsumptionResponse> responseHandle) { Evolution.Material consumed = responseHandle.Request.consumed; Evolution.Material produced = responseHandle.Request.produced; Map <Evolution.Material, uint> toxicLimits = responseHandle.Request.toxicLimits; var resources = ResourcesWriter.Data.resources; uint toxicity = 0; foreach (KeyValuePair <Evolution.Material, uint> resource in resources) { if (resource.Value > toxicLimits[resource.Key]) { toxicity += 1; } } if (resources[consumed] > 0) { resources[consumed] -= 1; resources[produced] += 1; ResourcesWriter.Send(new Resources.Update().SetResources(resources)); responseHandle.Respond(new ConsumptionResponse(false, toxicity)); } else { responseHandle.Respond(new ConsumptionResponse(true, toxicity)); } }
public void LoginClick() { Debug.Log("login clicked"); Utils.ShowMessagePanel("登陆中...", messagePanel); //iOS版本,如果是iOS审核版本,那么就该使用审核版本的登陆 if (isAuditVersion && Application.platform == RuntimePlatform.IPhonePlayer) { var req = new { username = userNameInputField.text, password = passwordInputField.text }; ResponseHandle handler = (string msg) => { Utils.HideMessagePanel(messagePanel); LoginResponse resp = JsonConvert.DeserializeObject <LoginResponse>(msg); if (resp.status != 0) { Debug.LogError("登陆失败,errorMessage = " + resp.errorMessage); Utils.ShowConfirmMessagePanel(resp.errorMessage, confirmMessagePanel); return; } Player me = JsonConvert.DeserializeObject <Player> (msg); Player.Me = me; Scenes.Load("MainPage", new Dictionary <string, string>()); }; StartCoroutine(ServerUtils.PostRequest(ServerUtils.AuditLoginUrl(), JsonConvert.SerializeObject(req), handler)); } else { ssdk.Authorize(PlatformType.WeChat); } }
private bool MiddlesAccepted(ESBContext context, ResponseHandle responseHandle) { IMiddleHandle[] middles = ESBFactory.Instance.Middles; string msg = null; int code = 400; foreach (IMiddleHandle handle in middles) { if (!handle.CanHandle(context, out msg, out code)) { string json = ESBUtil.ParseJson(new { MiddleName = handle.GetType().FullName, Message = "O middle rejeitou a solicitação", Url = context.Url, Detail = msg }); responseHandle.Write(ESBUtil.CreateBytes(json), code); return(false); } } return(true); }
private void OnHarvest(ResponseHandle <Harvestable.Commands.Harvest, HarvestRequest, HarvestResponse> request) { var resourcesToGive = Mathf.Min(SimulationSettings.HarvestReturnQuantity, health.Data.currentHealth); health.AddCurrentHealthDelta(-resourcesToGive); request.Respond(new HarvestResponse(resourcesToGive)); }
public static IEnumerator PostRequest(string url, string json, ResponseHandle handle, ResponseHandle errorHandle = null) { Debug.Log("Post Request: url = " + url); var req = new UnityWebRequest(url, "POST"); byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); req.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); //Send the request then wait here until it returns yield return(req.SendWebRequest()); if (req.isNetworkError) { Debug.Log("Error While Sending: " + req.error); if (errorHandle != null) { errorHandle(req.error); } else { Debug.Log("errorHandler is null"); } } else { Debug.Log("Received: " + req.downloadHandler.text); if (handle != null) { handle(req.downloadHandler.text); } } }
public static IEnumerator Post(string url, Dictionary <string, string> post, ResponseHandle callback) { WWWForm form = new WWWForm(); foreach (KeyValuePair <string, string> postArg in post) { form.AddField(postArg.Key, postArg.Value); } WWW www = new WWW(url, form); yield return(www); if (www.error != null) { Debug.Log("error is :" + www.error); if (callback != null) { callback(null); } } else { if (callback != null) { callback(www.text); } } }
private void CheckPlayerInGame() { ResponseHandle checkUserInGame = delegate(string jsonString){ Debug.Log("CheckPlayerInGameResponse: " + jsonString); //加入玩家已经游戏了,那么跳转到Gameplay Scene。否则什么都不需要坐。 CheckUserInGameResponse resp = JsonConvert.DeserializeObject <CheckUserInGameResponse>(jsonString); Dictionary <string, string> parameters = new Dictionary <string, string>(); if (resp.isInGame) { parameters["roomNo"] = resp.roomNo; parameters["serverUrl"] = resp.serverUrl; Scenes.Load("Gameplay", parameters); } else { if (!string.IsNullOrEmpty(LoginController.roomNo)) { JoinRoom(LoginController.roomNo); } } }; StartCoroutine(ServerUtils.PostRequest(ServerUtils.GetCheckUserInGameUrl() + "?req=" + JsonConvert.SerializeObject(new { userId = Player.Me.userId }), "{}", checkUserInGame)); }
public void CreateRoomClick() { ShowMessagePanel("正在创建房间..."); //创建房间 Debug.Log("create room click"); ResponseHandle createRoom = delegate(string jsonString){ Debug.Log("CreateRoomResponse: " + jsonString); HideMessagePanel(); //加入玩家已经游戏了,那么跳转到Gameplay Scene。否则什么都不需要坐。 CreateRoomResponse resp = JsonConvert.DeserializeObject <CreateRoomResponse>(jsonString); Dictionary <string, string> parameters = new Dictionary <string, string>(); if (resp.status == 0) { parameters["roomNo"] = resp.roomNo; parameters["serverUrl"] = resp.serverUrl; Scenes.Load("Gameplay", parameters); } }; Debug.Log("createRoomUrl: " + ServerUtils.GetCreateRoomUrl()); var req = new { userId = Player.Me.userId, jushu = int.Parse(GetGameProperty("gameproperty_jushu")), fangfei = GetGameProperty("gameproperty_fangfei"), fengshu = GetGameProperty("gameproperty_fs"), qz = GetGameProperty("gameproperty_qz"), wanfa = GetGameProperty("gameproperty_wanfa"), clientInfo = Utils.GetClientInfo(), userInfo = Utils.GetUserInfo() }; StartCoroutine(PostRequest(ServerUtils.GetCreateRoomUrl(), JsonConvert.SerializeObject(req), createRoom)); }
private void JoinRoom(string roomNo) { Debug.Log("JoinRoom roomNo = " + roomNo); ShowMessagePanel("查找房间中..."); //检查房间是否存在, 如果存在就跳转到游戏的界面 ResponseHandle handler = delegate(string jsonString){ Debug.Log("GetRoomResponse: " + jsonString); //加入玩家已经游戏了,那么跳转到Gameplay Scene。否则什么都不需要坐。 GetRoomResponse resp = JsonConvert.DeserializeObject <GetRoomResponse>(jsonString); Dictionary <string, string> parameters = new Dictionary <string, string>(); if (resp.isExist) { parameters["roomNo"] = resp.roomNo; parameters["serverUrl"] = resp.serverUrl; Scenes.Load("Gameplay", parameters); } else { //房间不存在 ShowConfirmMessagePanel("该房间不存在"); } }; ResponseHandle errorHandler = delegate(string error) { Debug.Log("errorHandler is called"); HideMessagePanel(); ShowConfirmMessagePanel("连接服务器失败,请检查你的网络"); }; StartCoroutine(ServerUtils.PostRequest(ServerUtils.GetRoomUrl(), JsonConvert.SerializeObject(new { roomNo = roomNo }), handler, errorHandler)); }
private void RequestEnded(ResponseHandle <PlayerCreation.Commands.CreatePlayer, CreatePlayerRequest, CreatePlayerResponse> responseHandle, ResponseCode responseCode, Option <StatusCode> failureCode = new Option <StatusCode>()) { Option <int> intFailureCode = failureCode.HasValue ? (int)failureCode.Value : new Option <int>(); inFlightClientRequests.Remove(responseHandle.CallerInfo.CallerWorkerId); responseHandle.Respond(new CreatePlayerResponse(responseCode, intFailureCode)); }
public static void Authorize(string appKey, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.APP_KEY, appKey); rp.callback = handle; apiCaller.Authorize(rp); }
public static void GetRecommends(string token, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.TOKEN, token); rp.callback = handle; apiCaller.GetRecommends(rp); }
public static void GetCategory(string token, int cid, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.CID, "" + cid); rp.data.Add(Param.TOKEN, token); rp.callback = handle; apiCaller.GetCategory(rp); }
public static void GetProductInScene(string token, int sceneId, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.SCENE_ID, "" + sceneId); rp.data.Add(Param.TOKEN, token); rp.callback = handle; apiCaller.GetProductInScene(rp); }
public static void GetProducer(string token, int producerId, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.PRODUCER_ID, "" + producerId); rp.data.Add(Param.TOKEN, token); rp.callback = handle; apiCaller.GetProducer(rp); }
private void HandleSendChat(ResponseHandle <Chat.Commands.SendChat, ChatMessage, Nothing> request) { var message = request.Request.message; var update = new Chat.Update(); update.AddChatSent(new ChatMessage(message.Substring(0, Mathf.Min(15, message.Length)))); chat.Send(update); request.Respond(new Nothing()); }
private void OnCreatePlayer(ResponseHandle <PlayerCreation.Commands.CreatePlayer, CreatePlayerRequest, CreatePlayerResponse> responseHandle) { var clientWorkerId = responseHandle.CallerInfo.CallerWorkerId; var playerEntityTemplate = EntityTemplateFactory.CreatePlayerTemplate(clientWorkerId); SpatialOS.Commands.CreateEntity(PlayerCreationWriter, playerEntityTemplate) .OnSuccess(_ => responseHandle.Respond(new CreatePlayerResponse((int)StatusCode.Success))) .OnFailure(failure => responseHandle.Respond(new CreatePlayerResponse((int)failure.StatusCode))); }
public async Task Dispatch(ESBContext context, ResponseHandle responseHandle, DispatchType dispatchType) { if (commands.TryGetValue(dispatchType, out IDispachCommand command)) { await command.Dispatch(context, responseHandle); } }
private void OnYieldHarvest(ResponseHandle <Harvestable.Commands.YieldHarvest, YieldHarvestRequest, HarvestResponse> request) { var resourcesToGive = Mathf.Min(SimulationSettings.HarvestReturnQuantity, remainingResources); remainingResources = Mathf.Max(harvestable.Data.resources - resourcesToGive, 0); harvestable.Send(new Harvestable.Update().SetResources(remainingResources)); request.Respond(new HarvestResponse(resourcesToGive)); }
private void OnCreatePlayer(ResponseHandle <PlayerCreation.Commands.CreatePlayer, CreatePlayerRequest, CreatePlayerResponse> responseHandle) { var clientWorkerId = responseHandle.CallerInfo.CallerWorkerId; Vector3 initialPosition = new Vector3((Random.Range(-1f, 1f) * 0.5f) * Random.Range(-200f, 200f), -5f, (Random.Range(-1f, 1f) * 0.5f) * Random.Range(-200f, 200f)); var playerEntityTemplate = EntityTemplateFactory.CreatePlayerTemplate(clientWorkerId, initialPosition); SpatialOS.Commands.CreateEntity(PlayerCreationWriter, playerEntityTemplate) .OnSuccess(_ => responseHandle.Respond(new CreatePlayerResponse((int)StatusCode.Success))) .OnFailure(failure => responseHandle.Respond(new CreatePlayerResponse((int)failure.StatusCode))); }
private void OnPlayerCreation(ResponseHandle <PlayerLifeCycle.Commands.SpawnPlayer, SpawnPlayerRequest, SpawnPlayerResponse> responseHandle, ICommandCallbackResponse <EntityId> response) { if (response.StatusCode != StatusCode.Success) { Debug.LogError("player spawner failed to create entity: " + response.ErrorMessage); return; } playerEntityIds.Add(responseHandle.CallerInfo.CallerWorkerId, response.Response.Value); responseHandle.Respond(new SpawnPlayerResponse(response.Response.Value)); }
public static void CheckUpdate(string appName, string appVersion, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.APP_NAME, appName); rp.data.Add(Param.APP_VERSION, appVersion); rp.callback = handle; apiCaller.CheckUpdate(rp); }
// Command callback for handling heartbeats from clients indicating client is connect and missed heartbeat counter should be reset private void OnHeartbeat(ResponseHandle <PlayerLifecycle.Commands.Heartbeat, HeartbeatRequest, HeartbeatResponse> responseHandle) { // Heartbeats are issued by clients authoritative over the player entity and should only be sending heartbeats for themselves if (responseHandle.Request.senderEntityId == thisEntityId) { // Reset missed heartbeat counter to avoid entity being deleted PlayerLifecycleWriter.Send(new PlayerLifecycle.Update().SetCurrentMissedHeartbeats(0)); } // Acknowledge command receipt responseHandle.Respond(new HeartbeatResponse()); }
public async Task GetResponseAsync_NeverGetsAResponse_ThrowsTimeout() { // arrange var subscriber = new SubscriberFake(); var handle = new ResponseHandle <TestReply>(subscriber, ChannelName); // act // assert await Assert.ThrowsAsync <TimeoutException>(() => handle.GetResponseAsync().WithTimeout(TimeSpan.FromSeconds(2))); }
public static void GetCategorys(string token, int?parentCid, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.TOKEN, token); if (parentCid != null) { rp.data.Add(Param.PARENT_CID, "" + (int)parentCid); } rp.callback = handle; apiCaller.GetCategorys(rp); }
public static void GetScenes(string token, int?sceneTypeId, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.TOKEN, token); if (sceneTypeId != null) { rp.data.Add(Param.SCENE_TYPE_ID, "" + sceneTypeId); } rp.callback = handle; apiCaller.GetScenes(rp); }
public static void GetAllScenes(string token, DateTime?modified, ResponseHandle handle) { ApiCaller.RequestParams rp = new ApiCaller.RequestParams(); rp.data = new Dictionary <string, string>(); rp.data.Add(Param.TOKEN, token); if (modified != null) { rp.data.Add(Param.LATEST_MODIFIED, StringUtil.DateTimeToString((DateTime)modified)); } rp.callback = handle; apiCaller.GetScenes(rp); }
private void CreatePlayerEntity(string clientWorkerId, ResponseHandle <PlayerCreation.Commands.CreatePlayer, CreatePlayerRequest, CreatePlayerResponse> responseHandle) { var playerEntityTemplate = EntityTemplateFactory.CreatePlayerTemplate(clientWorkerId, gameObject.EntityId()); SpatialOS.Commands.CreateEntity(PlayerCreationWriter, playerEntityTemplate) .OnSuccess(response => { AddPlayerEntityId(clientWorkerId, response.CreatedEntityId); RequestEnded(responseHandle, ResponseCode.SuccessfullyCreated); }) .OnFailure(failure => RequestEnded(responseHandle, ResponseCode.Failure, failure.StatusCode)); }
private void CommandReceiver_OnTakeControl(ResponseHandle <Controllable.Commands.TakeControl, ControlRequest, Nothing> obj) { Debug.LogWarning("RECEIVED COMMAND " + obj.Request.action); if (obj.Request.action == "release") { ReleaseControl(ControllableWriter.EntityId); } else { GainControl(ControllableWriter.EntityId, obj.CallerInfo.CallerWorkerId); } obj.Respond(new Nothing()); }