/// <summary> /// Called when the server receives an unserialized request. /// </summary> /// <param name="requestBytes">The serialized request.</param> private void OnRequest(byte[] requestBytes) { try { using (var input = new EnhancedMemoryStream(requestBytes)) { int typeCode = input.ReadInt32(); SharedMemMessage request; SharedMemMessage response; if (typeCode < 0) { request = new SharedMemErrorMessage(); } else { request = messageFactory.Create(typeCode); } request.InternalReadFrom(input); request.ReadFrom(input); try { response = requestHandler(request); if (response == null) { throw new NullReferenceException("Server request handler returned a NULL response message."); } } catch (Exception e) { response = new SharedMemErrorMessage(); response.InternalError = string.Format("{0}: {1}", e.GetType().FullName, e.Message); } response.InternalRequestId = request.InternalRequestId; response.InternalClientInbox = request.InternalClientInbox; using (var output = new EnhancedMemoryStream(response.SerializedCapacityHint)) { output.WriteInt32(response.TypeCode); response.InternalWriteTo(output); response.WriteTo(output); // This call is synchronous but should execute very quickly (microseconds). outbox.Send(response.InternalClientInbox, output.ToArray()); } } } catch (Exception e) { SysLog.LogException(e); } }
/// <summary> /// Called when the client receives a response. /// </summary> /// <param name="responseBytes">The serialized response.</param> private void OnResponse(byte[] responseBytes) { try { using (var input = new EnhancedMemoryStream(responseBytes)) { int typeCode = input.ReadInt32(); SharedMemMessage response; PendingOperation operation; if (typeCode < 0) { response = new SharedMemErrorMessage(); } else { response = messageFactory.Create(typeCode); } response.InternalReadFrom(input); response.ReadFrom(input); lock (syncLock) { if (!pendingOperations.TryGetValue(response.InternalRequestId, out operation)) { // The response received does not correlate to a pending operation // (probably due to the client side timing it out). We'll just // ignore it. return; } } if (response.InternalError != null) { operation.Tcs.TrySetException(new SharedMemException(response.InternalError)); } else { operation.Tcs.TrySetResult(response); } } } catch (Exception e) { SysLog.LogException(e); } }