示例#1
0
 public async Task RecieveAsync(ClientConnectionContext context, RecieveDelegate next)
 {
     using (var cryptoStream = new CryptoStream(context.Stream, new FromBase64Transform(), CryptoStreamMode.Read))
     {
         await next(new ClientConnectionContext(context.ClientWebSocket, cryptoStream));
     }
 }
示例#2
0
		private IMessage Run (MessageQueueTransactionType transactionType,
		                      RecieveDelegate r)
		{
			switch (transactionType) {
			case MessageQueueTransactionType.Single:
				using (RabbitMQMessageQueueTransaction tx = GetTx ()) {
					bool success = false;
					try {
						IMessage msg = Run (tx, r);
						tx.Commit ();
						success = true;
						return msg;
					} finally {
						if (!success)
							tx.Abort ();
					}
				}

			case MessageQueueTransactionType.None:
				return Run (r);

			default:
				throw new NotSupportedException(transactionType + " not supported");
			}
		}		
示例#3
0
		private IMessage Run (IMessageQueueTransaction transaction, 
		                      RecieveDelegate r)
		{
			TxReceiver txr = new TxReceiver (this, r);
			RabbitMQMessageQueueTransaction tx = 
				(RabbitMQMessageQueueTransaction) transaction;
			return tx.RunReceive (txr.ReceiveInContext);			
		}
示例#4
0
		private IMessage Run (RecieveDelegate r)
		{
			ConnectionFactory cf = new ConnectionFactory ();
			using (IConnection cn = cf.CreateConnection (QRef.Host)) {
				using (IModel model = cn.CreateModel ()) {
					return r (this, model);
				}
			}
		}
示例#5
0
 private IMessage Run(RecieveDelegate r)
 {
     using (IConnection cn = CreateConnection(QRef))
     {
         using (IModel model = cn.CreateModel())
         {
             return(r(this, model));
         }
     }
 }
示例#6
0
			public TxReceiver(RabbitMQMessageQueue q, RecieveDelegate doReceive) {
				this.q = q;
				this.doReceive = doReceive;
			}
示例#7
0
        private async Task Receive(Func <Stream, Task> handleMessage, CancellationToken ct)
        {
            Exception closingException = null;

            while (!ct.IsCancellationRequested && _clientWebSocket.State == WebSocketState.Open)
            {
                try
                {
                    ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[1024 * 4]);

                    using (var stream = _clientWebSocket.GetReadStream())
                    {
                        // Wait for data
                        await stream.WaitForDataAsync(ct);

                        var             receiveIterator  = _middleware.GetEnumerator();
                        RecieveDelegate receiveDelegator = null;
                        receiveDelegator = async transformedMessage =>
                        {
                            if (receiveIterator.MoveNext())
                            {
                                using (_logger?.Tracer($"Middleware[{receiveIterator.Current.GetType()}].RecieveAsync(...)"))
                                {
                                    await receiveIterator.Current.RecieveAsync(new ConnectionContext(_clientWebSocket, transformedMessage.Stream), receiveDelegator).ConfigureAwait(false);
                                }
                            }
                            else
                            {
                                using (_logger?.Tracer("Connection.InternalReceive(...)"))
                                {
                                    await handleMessage(transformedMessage.Stream).ConfigureAwait(false);
                                }
                            }
                        };

                        await receiveDelegator(new ConnectionContext(_clientWebSocket, stream))
                        .ContinueWith(task =>
                        {
                            // Dispose of our middleware iterator before we handle possible exceptions
                            receiveIterator.Dispose();

                            // Unwrap and allow the outer catch to handle if we have an exception
                            task.WaitAndUnwrapException();
                        })
                        .ConfigureAwait(false);
                    }
                }
                catch (WebSocketException e) when(e.Message == "The remote party closed the WebSocket connection without completing the close handshake.")
                {
                    _logger.LogWarning("Observed WebSocketException - likely server closing our connection");

                    // Eat the exception because we're closing
                    closingException = new WebSocketClosedException("Observed WebSocketException - likely server closing our connection", e);

                    try
                    {
                        if (_clientWebSocket.State == WebSocketState.CloseReceived)
                        {
                            // Attempt to be "good" and close
                            await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, ct);
                        }
                        else
                        {
                            _clientWebSocket.Abort();
                        }
                    }
                    catch (Exception) { }

                    // Fire the closing event
                    FireClosed(e);

                    // But we cancel out because the socket is closed
                    break;
                }
                catch (WebSocketClosedException e)
                {
                    _logger.LogWarning("Observed WebSocketClosedException - likely OK");

                    // Eat the exception because we're closing
                    closingException = e;

                    try
                    {
                        if (_clientWebSocket.State == WebSocketState.CloseReceived)
                        {
                            // Attempt to be "good" and close
                            await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, ct);
                        }
                    }
                    catch (Exception) { }

                    // Fire the closing event
                    FireClosed(e);

                    // But we cancel out because the socket is closed
                    break;
                }
                catch (Exception e)
                {
                    _logger.LogError(new EventId(), e, $"Observed {e.GetType()}!");

                    Error?.Invoke(e);
                }
            }

            // We're closing so we need to unblock any pending TaskCompletionSources
            InvocationRequest[] calls;

            lock (_pendingCallsLock)
            {
                calls = _pendingCalls.Values.ToArray();
                _pendingCalls.Clear();
            }

            foreach (var request in calls)
            {
                request.Registration.Dispose();
                request.Completion.TrySetException(closingException ?? new WebSocketClosedException("The WebSocket has been closed!"));
            }
        }
示例#8
0
		private IMessage Run (RecieveDelegate r)
		{
			using (IConnection cn = CreateConnection (QRef)) {
				using (IModel model = cn.CreateModel ()) {
					return r (this, model);
				}
			}
		}
示例#9
0
 public void registerDelegate(RecieveDelegate del)
 {
   the_delegate = del;    
 }
示例#10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UdpEngine"/> class.
 /// </summary>
 /// <param name="talkPort">
 /// The talk port.
 /// </param>
 /// <param name="listenPort">
 /// The listen port.
 /// </param>
 public UdpEngine(int talkPort, int listenPort, RecieveDelegate callback)
 {
     this.talkPort        = talkPort;
     this.listenPort      = listenPort;
     this.receiveCallback = callback;
 }