/// <summary> /// Tracking callback for GET operations. /// </summary> /// <param name="response">The response received from the server.</param> public static void GetCallback(AsyncResponse<Table> response) { // Only track the Put if the request was successful! if (response.Status == ResponseStatus.Success) { // Unpack result to retrieve compressed and uncompressed value sizes and increment counters. byte[] data = response.Result.GetValue<byte[]>(1,0); long compressedSize = data.Length; // Encoding.UTF8.GetBytes(response.Result).LongLength; long uncompressedSize = 0; switch (State.ValueEncoding) { case ApplicationState.DataEncoding.Gzip: uncompressedSize = data.UnGzip().LongLength; break; case ApplicationState.DataEncoding.Deflate: uncompressedSize = data.UnDeflate().LongLength; break; default: uncompressedSize = compressedSize; break; } // Increment tracking counters Interlocked.Increment(ref State.GetCount); Interlocked.Add(ref State.GetBytesCompressed, compressedSize); Interlocked.Add(ref State.GetBytesUncompressed, uncompressedSize); } else { Console.WriteLine(response.ServerStatusString); } }
public static void CreateImportDefinition(SoapClient soapClient, string iImportDefinitionName, string iImportDefinitionCustomerKey, string iTargetDataExtensionCustomerKey, string iImportFileName) { ImportDefinition id = new ImportDefinition(); id.Name = iImportDefinitionName; id.CustomerKey = iImportDefinitionCustomerKey; // Optional value, if AllowErrors is true then it will not stop the import when // a single row has an error id.AllowErrors = true; id.AllowErrorsSpecified = true; // For this example, we are sending to a data extension // Value for CustomerKey will be for a data extension already created in your account DataExtension de = new DataExtension(); de.CustomerKey = iTargetDataExtensionCustomerKey; id.DestinationObject = de; AsyncResponse ar = new AsyncResponse(); ar.ResponseType = AsyncResponseType.email; ar.ResponseAddress = "*****@*****.**"; id.Notification = ar; FileTransferLocation ftl = new FileTransferLocation(); ftl.CustomerKey = "ExactTarget Enhanced FTP"; id.RetrieveFileTransferLocation = ftl; // Specify how the import will be handled // If data extension has no primary key specified then only "Overwrite" will work id.UpdateType = ImportDefinitionUpdateType.AddAndUpdate; id.UpdateTypeSpecified = true; id.FieldMappingType = ImportDefinitionFieldMappingType.InferFromColumnHeadings; id.FieldMappingTypeSpecified = true; id.FileSpec = iImportFileName; id.FileType = FileType.CSV; id.FileTypeSpecified = true; string sStatus = ""; string sRequestId = ""; CreateResult[] aoResults = soapClient.Create(new CreateOptions(), new APIObject[] { id }, out sRequestId, out sStatus); Console.WriteLine("Status: " + sStatus); Console.WriteLine("Request ID: " + sRequestId); foreach (CreateResult cr in aoResults) { Console.WriteLine("StatusCode: " + cr.StatusCode); Console.WriteLine("ErrorCode: " + cr.ErrorCode); Console.WriteLine("StatusMessage: " + cr.StatusMessage); } }
public void detailedHistory(string channel, AsyncResponse callback, long start = -1, long stop = -1, long count = 10, bool reverse = false ) { string[] request = {"v2","history","sub-key",subscribe_key,"channel",encode(channel)}; string query = "reverse=" + reverse.ToString() + "&count=" + count.ToString(); if( start >= 0 ) { query += "&" + "start=" + start.ToString(); } if( stop >= 0 ) { query += "&" + "stop=" + stop.ToString(); } _request(request,callback,query); }
/// <summary> /// Tracking callback for PUT operations. /// </summary> /// <param name="response">The response received from the server.</param> public static void PutCallback(AsyncResponse<Null> response) { // Only track the Put if the request was successful! if (response.Status == ResponseStatus.Success) { // Retrieve the pair that was passed as state object for our callback SizeInfo info = (SizeInfo)response.AsyncState; // Increment tracking counters Interlocked.Increment(ref State.PutCount); Interlocked.Add(ref State.PutBytesCompressed, info.CompressedSize); Interlocked.Add(ref State.PutBytesUncompressed, info.UncompressedSize); } }
private AsyncResponse DoSend(RtspRequest request, RtspResponseCallback resCallback = null) { int cseq = GetNextCSeq(); request.CSeq = _cseq; AsyncResponse callback = new AsyncResponse(cseq, resCallback); if (!_connection.WriteMessage(request)) { callback.Dispose(); throw new RtspClientException("Unable to send request to client"); } _callbacks[cseq] = callback; return(callback); }
internal static RateLimit ReadRateLimit(AsyncResponse response) { if (!new[] { XRateLimitLimit, XRateLimitRemaining, XRateLimitReset } .All(x => response.Headers.ContainsKey(x))) { return(null); } var limit = response.Headers[XRateLimitLimit]; var remaining = response.Headers[XRateLimitRemaining]; var reset = response.Headers[XRateLimitReset]; return(new RateLimit() { Limit = int.Parse(limit, NumberFormatInfo.InvariantInfo), Remaining = int.Parse(remaining, NumberFormatInfo.InvariantInfo), Reset = GetUnixTime(long.Parse(reset, NumberFormatInfo.InvariantInfo)) }); }
internal static RateLimit ReadRateLimit(AsyncResponse response) { if (!new[] { XRateLimitLimit, XRateLimitRemaining, XRateLimitReset } .All(x => response.Headers.ContainsKey(x))) { return(null); } var limit = response.Headers[XRateLimitLimit]; var remaining = response.Headers[XRateLimitRemaining]; var reset = response.Headers[XRateLimitReset]; return(new RateLimit() { Limit = int.Parse(limit), Remaining = int.Parse(remaining), Reset = InternalUtils.GetUnixTime(long.Parse(reset)) }); }
/// <summary> /// Asynchronously sends RTSP request. Invokes callback if a response is received /// from the server. /// </summary> /// <param name="request">The request to send</param> /// <param name="callback">Callback to be called when a response is available</param> public void SendAsync(RtspRequest request, RtspResponseCallback callback) { AsyncResponse asyncRes = null; try { if (_authResponse != null && _credentials != null) { // Set the authorization header if we have a cached auth response. request.Authorization = _authResponse.Generate(request.Method, request.URI); } asyncRes = DoSend(request, (res) => { var status = res.ResponseStatus; if (status.Is(RtspResponse.Status.Unauthorized) && _credentials != null) { _authResponse = AuthChallenge.Parse(_credentials, res.WWWAuthenticate); if (_authResponse != null) { LOG.Warn($"Received RTSP Unauthorized response re-trying with creds {_credentials.Username}:{_credentials.Password}"); request.Authorization = _authResponse.Generate(request.Method, request.URI); asyncRes = DoSend(request, callback); } } else { callback.Invoke(res); } }); } catch (Exception e) { if (asyncRes != null) { RemoveCallback(asyncRes.CSeq); } throw e; } }
public RtspResponse Send(RtspRequest request, TimeSpan timeout) { AsyncResponse asyncRes = null; try { if (_authResponse != null && _credentials != null) { // Set the authorization header if we have a cached auth response. request.Authorization = _authResponse.Generate(request.Method, request.URI); } asyncRes = DoSend(request); RtspResponse response = asyncRes.Get(timeout); var status = response.ResponseStatus; if (status.Is(RtspResponse.Status.Unauthorized) && _credentials != null) { _authResponse = AuthChallenge.Parse(_credentials, response.WWWAuthenticate); if (_authResponse != null) { LOG.Warn($"Received RTSP Unauthorized response re-trying with creds {_credentials.Username}:{_credentials.Password}"); request.Authorization = _authResponse.Generate(request.Method, request.URI); asyncRes = DoSend(request); response = asyncRes.Get(timeout); } } return(response); } catch (Exception e) { if (asyncRes != null) { RemoveCallback(asyncRes.CSeq); } throw e; } }
protected internal virtual void removeDuplicates() { foreach (FetchAndLockRequest newRequest in newRequests) { // remove any request from pendingRequests with the same worker id IEnumerator <FetchAndLockRequest> iterator = pendingRequests.GetEnumerator(); while (iterator.MoveNext()) { FetchAndLockRequest pendingRequest = iterator.Current; if (pendingRequest.Dto.WorkerId.Equals(newRequest.Dto.WorkerId)) { AsyncResponse asyncResponse = pendingRequest.AsyncResponse; asyncResponse.cancel(); //JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only: iterator.remove(); } } } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldResumeAsyncResponseDueToAvailableTasks() public virtual void shouldResumeAsyncResponseDueToAvailableTasks() { // given IList <LockedExternalTask> tasks = new List <LockedExternalTask>(); tasks.Add(lockedExternalTaskMock); doReturn(tasks).when(fetchTopicBuilder).execute(); AsyncResponse asyncResponse = mock(typeof(AsyncResponse)); handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); // when handler.acquire(); // then verify(asyncResponse).resume(argThat(IsCollectionWithSize.hasSize(1))); assertThat(handler.PendingRequests.Count, @is(0)); verify(handler).suspend(long.MaxValue); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldResumeAsyncResponseDueToTimeoutExceeded() public virtual void shouldResumeAsyncResponseDueToTimeoutExceeded() { // given - no pending requests // assume assertThat(handler.PendingRequests.Count, @is(0)); // when AsyncResponse asyncResponse = mock(typeof(AsyncResponse)); handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT + 1), asyncResponse, processEngine); // then verify(handler, never()).suspend(anyLong()); assertThat(handler.PendingRequests.Count, @is(0)); ArgumentCaptor <InvalidRequestException> argumentCaptor = ArgumentCaptor.forClass(typeof(InvalidRequestException)); verify(asyncResponse).resume(argumentCaptor.capture()); assertThat(argumentCaptor.Value.Message, @is("The asynchronous response timeout cannot " + "be set to a value greater than " + FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT + " milliseconds")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldRejectRequestDueToShutdown() public virtual void shouldRejectRequestDueToShutdown() { // given AsyncResponse asyncResponse = mock(typeof(AsyncResponse)); handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); handler.acquire(); // assume assertThat(handler.PendingRequests.Count, @is(1)); // when handler.rejectPendingRequests(); // then ArgumentCaptor <RestException> argumentCaptor = ArgumentCaptor.forClass(typeof(RestException)); verify(asyncResponse).resume(argumentCaptor.capture()); assertThat(argumentCaptor.Value.Status, @is(Status.INTERNAL_SERVER_ERROR)); assertThat(argumentCaptor.Value.Message, @is("Request rejected due to shutdown of application server.")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotCancelPreviousPendingRequestWhenWorkerIdsDiffer() public virtual void shouldNotCancelPreviousPendingRequestWhenWorkerIdsDiffer() { // given doReturn(Collections.emptyList()).when(fetchTopicBuilder).execute(); handler.parseUniqueWorkerRequestParam("true"); AsyncResponse asyncResponse = mock(typeof(AsyncResponse)); handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "aWorkerId"), asyncResponse, processEngine); handler.acquire(); handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "anotherWorkerId"), mock(typeof(AsyncResponse)), processEngine); // when handler.acquire(); // then verify(asyncResponse, never()).cancel(); assertThat(handler.PendingRequests.Count, @is(2)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldResumeAsyncResponseAfterBackoffDueToProcessEngineException() public virtual void shouldResumeAsyncResponseAfterBackoffDueToProcessEngineException() { // given doReturn(Collections.emptyList()).when(fetchTopicBuilder).execute(); AsyncResponse asyncResponse = mock(typeof(AsyncResponse)); handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); handler.acquire(); // assume assertThat(handler.PendingRequests.Count, @is(1)); verify(handler).suspend(5000L); // when doThrow(new ProcessEngineException()).when(fetchTopicBuilder).execute(); handler.acquire(); // then assertThat(handler.PendingRequests.Count, @is(0)); verify(handler).suspend(long.MaxValue); verify(asyncResponse).resume(any(typeof(ProcessEngineException))); }
public Result Request(AsyncResponse outAsyncResponse, Uid userId, ShopServiceMethod method, string requestPath, string postData, TimeSpan timeout) => default; // 0x00A147C0-0x00A14880 public Result Request(AsyncResponse outAsyncResponse, Uid userId, ShopServiceMethod method, string requestPath, TimeSpan timeout) => default; // 0x00A14920-0x00A149C0
public Result Request(AsyncResponse outAsyncResponse, Uid userId, ShopServiceMethod method, string requestPath, string postData) => default; // 0x00A14A50-0x00A14B00 public Result Request(AsyncResponse outAsyncResponse, Uid userId, ShopServiceMethod method, string requestPath) => default; // 0x00A14B00-0x00A14B80
protected internal virtual void acquire() { LOG.log(Level.FINEST, "Acquire start"); queue.drainTo(newRequests); if (newRequests.Count > 0) { if (isUniqueWorkerRequest) { removeDuplicates(); } ((IList <FetchAndLockRequest>)pendingRequests).AddRange(newRequests); newRequests.Clear(); } LOG.log(Level.FINEST, "Number of pending requests {0}", pendingRequests.Count); long backoffTime = MAX_BACK_OFF_TIME; //timestamp IEnumerator <FetchAndLockRequest> iterator = pendingRequests.GetEnumerator(); while (iterator.MoveNext()) { FetchAndLockRequest pendingRequest = iterator.Current; LOG.log(Level.FINEST, "Fetching tasks for request {0}", pendingRequest); FetchAndLockResult result = tryFetchAndLock(pendingRequest); LOG.log(Level.FINEST, "Fetch and lock result: {0}", result); if (result.wasSuccessful()) { IList <LockedExternalTaskDto> lockedTasks = result.Tasks; if (lockedTasks.Count > 0 || isExpired(pendingRequest)) { AsyncResponse asyncResponse = pendingRequest.AsyncResponse; asyncResponse.resume(lockedTasks); LOG.log(Level.FINEST, "resume and remove request with {0}", lockedTasks); //JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only: iterator.remove(); } else { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long msUntilTimeout = pendingRequest.getTimeoutTimestamp() - org.camunda.bpm.engine.impl.util.ClockUtil.getCurrentTime().getTime(); long msUntilTimeout = pendingRequest.TimeoutTimestamp - ClockUtil.CurrentTime.Ticks; backoffTime = Math.Min(backoffTime, msUntilTimeout); } } else { AsyncResponse asyncResponse = pendingRequest.AsyncResponse; Exception processEngineException = result.Throwable; asyncResponse.resume(processEngineException); LOG.log(Level.FINEST, "Resume and remove request with error {0}", processEngineException); //JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only: iterator.remove(); } } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long waitTime = Math.max(0, backoffTime); long waitTime = Math.Max(0, backoffTime); if (pendingRequests.Count == 0) { suspend(waitTime); } else { // if there are pending requests, try fetch periodically to ensure tasks created on other // cluster nodes and tasks with expired timeouts can be fetched in a timely manner suspend(Math.Min(PENDING_REQUEST_FETCH_INTERVAL, waitTime)); } }
public virtual FetchAndLockRequest setAsyncResponse(AsyncResponse asyncResponse) { this.asyncResponse = asyncResponse; return(this); }
public static void subscribe(string channel, AsyncResponse callback, AsyncResponse onConnected = null, AsyncResponse onError = null) { instance.subscribe(channel,callback,onConnected,onError); }
protected internal virtual void errorTooManyRequests(AsyncResponse asyncResponse) { string errorMessage = "At the moment the server has to handle too many requests at the same time. Please try again later."; asyncResponse.resume(new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, errorMessage)); }
public static void detailedHistory(string channel, AsyncResponse callback, long start = -1, long stop = -1, long count = 10, bool reverse = false ) { instance.detailedHistory(channel,callback,start,stop,count,reverse); }
public void time(AsyncResponse callback) { string[] request = { "time", "0" }; _request(request,callback); }
public virtual void fetchAndLock(FetchExternalTasksExtendedDto dto, AsyncResponse asyncResponse) { FetchAndLockHandler fetchAndLockHandler = FetchAndLockContextListener.FetchAndLockHandler; fetchAndLockHandler.addPendingRequest(dto, asyncResponse, processEngine); }
public static void here_now(string channel, AsyncResponse callback) { instance.here_now(channel,callback); }
public static void history(string channel, AsyncResponse callback, int limit = 10 ) { instance.history(channel,callback,limit); }
public void here_now(string channel, AsyncResponse callback) { string[] request = {"v2","presence","sub-key",subscribe_key,"channel",encode(channel)}; _request(request,callback); }
public RetrieveXMLData(Context context, LocationXMLAdapter adapter, AssetManager assets, AsyncResponse asyncResponse) { mContext = context; mAdapter = adapter; mAssets = assets; resDelegate = asyncResponse; }
private string GetContent(string URL) { string RESULT = null; HttpWebResponse Response; Stream ResponseStream; HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(URL); Request.Timeout = m_Timeout * 1000; Request.KeepAlive = false; try { Response = (HttpWebResponse)Request.GetResponse(); } catch { return(null); } if (Response.StatusCode == HttpStatusCode.OK) { ResponseStream = Response.GetResponseStream(); // Async Operations AsyncResponse AsyncCall = new AsyncResponse(this.GetResponse); IAsyncResult aResult = AsyncCall.BeginInvoke(ResponseStream, null, null); if (aResult.AsyncWaitHandle.WaitOne(m_Timeout * 1000, false)) { if (aResult.IsCompleted) { RESULT = AsyncCall.EndInvoke(aResult); } else { AsyncCall.EndInvoke(aResult); } } else { AsyncCall.EndInvoke(aResult); } ResponseStream.Close(); if (RESULT != null) { return(RESULT); } else { return(null); } } else { return(null); } }
public void subscribe(string channel, AsyncResponse callback, AsyncResponse onConnected = null, AsyncResponse onError = null) { if( !subscriptions.ContainsKey(channel) ) { subscriptions.Add(channel, new Hashtable()); } Hashtable subscription = (Hashtable)subscriptions[channel]; if(subscription["connected"] != null) { debug( "Already connected to " + channel ); return; } subscription["onError"] = onError; subscription["onConnected"] = onConnected; subscription["callback"] = callback; subscription["timetoken"] = "0"; subscription.Add("connected",true); subscription.Remove("first"); string[] request = {"subscribe",subscribe_key,encode(channel),"0",(string)subscription["timetoken"]}; StartCoroutine( substabizel(channel, request, "uuid="+uuid) ); }
public void OnSocketMessage(JSONObject message) { // Debug.Log("Network.onSocketMessage\n\nmessage: " + Service.PrettyJson(message)); var res = new AsyncResponse(message, this); Action <JSONObject> onResult = null; try { var type = message["type"].AsInt; string senderMessageId = null; if (message.HasKeyNotNull("senderMessageId")) { senderMessageId = message["senderMessageId"].ToString(); } switch (type) { case 1: if (message.HasKeyNotNull("senderName") && message["senderName"].ToString().Equals(_chatServerName)) { Debug.LogError("fireEvents with AsyncResponse not implemented yet"); FireEvents("message", message, res); } else { ActivePeerInGameCenter(); } break; case 2: string content = message["content"]; HandleDeviceRegisterMessage(long.Parse(content)); break; case 3: if (senderMessageId != null) { onResult = _ackCallback[senderMessageId]; } if (senderMessageId != null && onResult != null) { onResult(JSON.Parse(message["content"].ToString()).AsObject); _ackCallback.Remove(senderMessageId); } else { FireEvents("message", message); } break; case 4: case 5: //Debug.LogError("fireEvents with AsyncResponse not implemented yet"); FireEvents("message", message, res); break; case 6: if (senderMessageId != null) { onResult = _ackCallback[senderMessageId]; if (onResult != null) { onResult(Util.CreateReturnData(false, "", 0, new JSONObject())); _ackCallback.Remove(senderMessageId); } } break; } } catch (Exception e) { Debug.LogError("Exception: " + e.Message); //throw new ServiceException(e); } }
private void _request(string[] request, AsyncResponse callback = null, string query = "") { WebClient client = new WebClient (); string url = origin + String.Join("/", request) + "?" + query; debug( url ); client.Headers.Add("V","1.0"); client.Headers.Add("User-Agent","Unity3D"); client.DownloadStringCompleted += (s,e) => { if( callback != null ) { Hashtable response = new Hashtable(); if(e.Cancelled != false || e.Error != null) { response.Add("error", true); } else { response.Add("message", (ArrayList)JSON.JsonDecode((string)e.Result)); } callback( response ); } client.Dispose(); }; client.DownloadStringAsync(new Uri( url )); }
public void publish(string channel, object messageObject, AsyncResponse callback = null) { string message = JSON.JsonEncode( messageObject ); string signature = "0"; if(secure) { string[] plaintext = {publish_key,subscribe_key,secret_key,channel,message}; byte[] hash = sha256.ComputeHash( System.Text.Encoding.UTF8.GetBytes(String.Join("/",plaintext))); signature = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower(); } string[] request = {"publish",publish_key,subscribe_key,signature,encode(channel),"0",encode(message)}; _request(request, callback); }
public static void publish(string channel, object messageObject, AsyncResponse callback = null) { instance.publish(channel,messageObject,callback); }
public void SendAsyncResponse(string url, int interfaceId, string interfaceUniqueId, string orderUniqueId, string userName, string password, int accountID, DateTime eventDate, string comment, int eventCode, int statusCode) { AsyncResponse response = new AsyncResponse(); ResponseData responseData = new ResponseData(); PropertyResponse propertyResponse = new PropertyResponse(); string log = "Send Async - " + ", " + interfaceUniqueId + ", " + userName + ", " + password + ", "; Task <int> res; try { res = _logService.SaveLogEntry(interfaceId, log, interfaceUniqueId); HttpResponse httpResponse = new HttpResponse(); response.responseDateTime = System.DateTime.Now; response.responseData = new List <ResponseData>(); responseData.description = ""; response.internalAccountIdentifier = interfaceUniqueId; responseData.comment = comment; responseData.statusCode = statusCode; response.responseData.Add(responseData); response.responseData[0].propertyResponse = new List <PropertyResponse>(); response.responseData[0].propertyResponse.Add(new PropertyResponse()); response.responseData[0].propertyResponse[0].eventCode = eventCode; response.responseData[0].propertyResponse[0].uniqueID = new Guid(orderUniqueId); response.responseData[0].propertyResponse[0].customerFee = null; var payload = new { response = response }; JsonSerializerSettings jss = new JsonSerializerSettings(); jss.NullValueHandling = NullValueHandling.Ignore; httpResponse = _httpService.PostMessage(url, JsonConvert.SerializeObject(payload, jss), "", ""); if (httpResponse.success == true) { //check status code JToken avsResponse = JToken.Parse(httpResponse.responseData); int retval = 0; int.TryParse(avsResponse["response"]["responseData"][0]["statusCode"].ToString(), out retval); if (retval != 0) { res = _commonRepository.SaveInterfaceData(interfaceId, JsonConvert.SerializeObject(payload, jss), "App", "Resend"); } } } catch (Exception ex) { log = "Send Async error - " + ex.Message + "\n" + ", " + interfaceUniqueId + ", " + userName + ", " + password + ", "; res = _logService.SaveLogEntry(interfaceId, log, interfaceUniqueId); } }
/** * <div style='width: 100%;text-align: right'> این متد بعد از دریافت پیامی جدید از سوی حریف , فراخوانی می شود</div> * @param receivedData * <ul> * <li>{JSONObject|string} data - پیام ارسال شده از سوی حریف</li> * <li>{JSONObject|string} dataId - شناسه پیام ارسال شده</li> * </ul> * * @param res کابکی که بعد از دریافت پیام جدید باید فراخوانی شود.با فرخوانی این متد فرد مقابل می فهمد که پیام به دست شما رسیده است * */ private void OnReceiveData(JSONObject receivedData, AsyncResponse res) { _onReceiveDataAction(receivedData, res); }
public void history(string channel, AsyncResponse callback, int limit = 10 ) { string[] request = {"history",subscribe_key,encode(channel),"0",limit.ToString()}; _request(request,callback); }
public void presence(string channel, AsyncResponse callback, AsyncResponse onConnected = null, AsyncResponse onError = null) { channel += "-pnpres"; subscribe(channel,callback,onConnected,onError); }
private void HandlePushMessageContent(JSONObject Params, AsyncResponse res) { // Debug.Log("handlePushMessageContent_1 " + PrettyJson(Params)); try { var message = JSON.Parse(Params["content"]).AsObject; var senderMessageId = Params["senderMessageId"].AsInt.ToString(); var messageType = message["type"].AsInt; var data = JSON.Parse(message["content"]).AsObject; if (messageType == PushMessageContentTypes.DataPack) { OnReceiveDataPackAction(data, res); } else { if (!_gameCenterMessagesId.ContainsKey(senderMessageId)) { switch (messageType) { case PushMessageContentTypes.RequestIdState: Debug.Log("REQUEST_ID_STATE " + data); OnReceiveRequestIdStateAction(data); break; case PushMessageContentTypes.MatchNew: Debug.Log("MATCH_NEW " + data); OnReceiveNewMatchAction(data); break; case PushMessageContentTypes.MatchStart: Debug.Log("MATCH_START " + data); OnReceiveStartMatchAction(data); break; case PushMessageContentTypes.MatchResume: Debug.Log("MATCH_RESUME " + data); OnReceiveResumeMachAction(data); break; case PushMessageContentTypes.MatchPause: Debug.Log("MATCH_PAUSE " + data); OnReceivePauseMatchAction(data); break; case PushMessageContentTypes.MatchRequest: Debug.Log("MATCH_REQUEST " + data); OnReceiveRequestMatchAction(data); break; case PushMessageContentTypes.MatchResult: Debug.Log("MATCH_RESULT " + data); OnReceiveMatchResultAction(data); break; case PushMessageContentTypes.Message: Debug.Log("MESSAGE " + data); OnReceiveMessageAction(data); break; case PushMessageContentTypes.MatchReconnect: Debug.Log("MATCH_RECONNECT " + data); OnReceiveResumeMachAction(data); break; case PushMessageContentTypes.MatchLeave: Debug.Log("MATCH_LEAVE " + data); OnReceiveLeaveMachAction(data); break; } _gameCenterMessagesId.Add(senderMessageId, true); res.Call(); } else { res.Call(); } } } catch (Exception e) { Debug.LogError("Exception: " + e.Message); } }