private async void StartReceiving()
		{
			var buffer = new byte[8192];
			var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
			using (var ms = new MemoryStream())
			{
				try
				{
					do
					{
						if (_socket.State != WebSocketState.Open)
						{
							await Task.Delay(10);
							continue;
						}
						var result = await _socket.ReceiveAsync(segment, _tokenSource.Token);
						if (result.CloseStatus != null && result.CloseStatus != WebSocketCloseStatus.Empty)
							break;
						if (result.Count > 0)
							ms.Write(segment.Array, segment.Offset, result.Count);
						if (result.EndOfMessage)
						{
							var data = new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length);
							var args = new DataReceivedArgs { Data = data, SessionID = _socket };
							Received.Invoke(this, args); // assuming synchronous usage of the data: that may not be correct
							ms.SetLength(0);
						}
					} while (!_tokenSource.IsCancellationRequested);
				}
				catch (OperationCanceledException)
				{
					// exit without propagating the exception
				}
			}
		}
Esempio n. 2
0
        private async void TransportSourceOnReceived(object sender, DataReceivedArgs args)
        {
            if (args.Data.Array == null)
            {
                return;
            }

            using (var stream = new MemoryStream(args.Data.Array, args.Data.Offset, args.Data.Count, false))
            {
                var message = Serializer.Deserialize <Message>(stream);
                message.SessionID = args.SessionID;
                var target = _handlers[message.Hub];
                await target.Handle(type =>                 // expecting delegate to not be held for usage later
                {
                    if (type == null || type.IsInstanceOfType(message))
                    {
                        return(message);
                    }
                    stream.Position = 0;
                    var ret         = (Message)Serializer.Deserialize(stream, type);
                    ret.SessionID   = args.SessionID;
                    return(ret);
                });
            }
        }
		private async void ListenForMessages(WebSocket socket)
		{
			TOP:
			try
			{
				if (!socket.IsConnected)
					return;

				var message = await socket.ReadMessageAsync(_tokenSource.Token);
				if (message != null)
				{
					using (var ms = new MemoryStream()) // length was throwing an exception
					{
						message.CopyTo(ms);
						var segment = new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);
						var args = new DataReceivedArgs { Data = segment, SessionID = socket };
						Received.Invoke(this, args);
					}
				}
				goto TOP;
			}
			catch (TaskCanceledException) { }
			catch (Exception)
			{
				goto TOP;
			}
		}
        private async void ListenForMessages(WebSocket socket)
        {
TOP:
            try
            {
                if (!socket.IsConnected)
                {
                    return;
                }

                var message = await socket.ReadMessageAsync(_tokenSource.Token);

                if (message != null)
                {
                    using (var ms = new MemoryStream())                     // length was throwing an exception
                    {
                        message.CopyTo(ms);
                        var segment = new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length);
                        var args    = new DataReceivedArgs {
                            Data = segment, SessionID = socket
                        };
                        Received.Invoke(this, args);
                    }
                }
                goto TOP;
            }
            catch (TaskCanceledException) { }
            catch (Exception)
            {
                goto TOP;
            }
        }
Esempio n. 5
0
        private void OnMessageReceived(object sender, MessageEventArgs e)
        {
            var args = new DataReceivedArgs {
                Data = new ArraySegment <byte>(e.RawData, 0, e.RawData.Length)
            };

            Received.Invoke(this, args);
        }
		protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
		{
			var args = new DataReceivedArgs
			{
				Data = new ArraySegment<byte>(e.RawData, 0, e.RawData.Length),
				SessionID = this
			};
			_source.FireRecieved(args);
		}
Esempio n. 7
0
        protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
        {
            var args = new DataReceivedArgs
            {
                Data      = new ArraySegment <byte>(e.RawData, 0, e.RawData.Length),
                SessionID = this
            };

            _source.FireRecieved(args);
        }
Esempio n. 8
0
        public override void on_data_available(DataReader reader)
        {
            var bytes = new Bytes();
            var info  = new SampleInfo();

            reader.take_next_sample_untyped(bytes, info);

            if (bytes.value != null)
            {
                var args = new DataReceivedArgs
                {
                    Data      = new ArraySegment <byte>(bytes.value, bytes.offset, bytes.length),
                    SessionID = info.instance_handle
                };
                Received.Invoke(this, args);
            }
        }
Esempio n. 9
0
        private async void StartReceiving()
        {
            var buffer  = new byte[8192];
            var segment = new ArraySegment <byte>(buffer, 0, buffer.Length);

            using (var ms = new MemoryStream())
            {
                try
                {
                    do
                    {
                        if (_socket.State != WebSocketState.Open)
                        {
                            await Task.Delay(10);

                            continue;
                        }
                        var result = await _socket.ReceiveAsync(segment, _tokenSource.Token);

                        if (result.CloseStatus != null && result.CloseStatus != WebSocketCloseStatus.Empty)
                        {
                            break;
                        }
                        if (result.Count > 0)
                        {
                            ms.Write(segment.Array, segment.Offset, result.Count);
                        }
                        if (result.EndOfMessage)
                        {
                            var data = new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length);
                            var args = new DataReceivedArgs {
                                Data = data, SessionID = _socket
                            };
                            Received.Invoke(this, args);                             // assuming synchronous usage of the data: that may not be correct
                            ms.SetLength(0);
                        }
                    } while (!_tokenSource.IsCancellationRequested);
                }
                catch (OperationCanceledException)
                {
                    // exit without propagating the exception
                }
            }
        }
Esempio n. 10
0
		private void StartReceivingMessages(Socket socket, byte[] buffer)
		{
			var task = new Task(() =>
			{
				while (!socket.IsDisposed)
				{
					var received = socket.ReceiveMessage(buffer);
					if (received >= 0)
					{
						var args = new DataReceivedArgs
						{
							Data = new ArraySegment<byte>(buffer, 0, received),
							SessionID = socket
						};
						Received.Invoke(this, args);
					}
				}
			}, TaskCreationOptions.LongRunning);
			task.Start();
		}
Esempio n. 11
0
        public override void OnDataAvailable(IDataReader entityInterface)
        {
            var        reader = (ByteDataReader)entityInterface;
            ByteData   data;
            SampleInfo info;
            var        success = reader.Take(out data, out info);

            if (success != ReturnCode.Ok)
            {
                throw new Exception("Not successful on read: " + success);
            }

            base.OnDataAvailable(entityInterface);

            if (data != null)
            {
                var args = new DataReceivedArgs
                {
                    Data      = new ArraySegment <byte>(data.Bytes, 0, data.Count),
                    SessionID = info.InstanceHandle
                };
                Received.Invoke(this, args);
            }
        }
 internal void FireRecieved(DataReceivedArgs args)
 {
     Received.Invoke(this, args);
 }
		private void OnDataReceived(object sender, DataReceivedEventArgs e)
		{
			var args = new DataReceivedArgs();
			args.Data = new ArraySegment<byte>(e.Data, 0, e.Data.Length);
			Received.Invoke(this, args);
		}
Esempio n. 14
0
 private void OnChildReceived(object sender, DataReceivedArgs e)
 {
     Received.Invoke(this, e);
 }
		internal void FireRecieved(DataReceivedArgs args)
		{
			Received.Invoke(this, args);
		}
		private void OnChildReceived(object sender, DataReceivedArgs e)
		{
			Received.Invoke(this, e);
		}
Esempio n. 17
0
		public override void OnDataAvailable(IDataReader entityInterface)
		{
			var reader = (ByteDataReader)entityInterface;
			ByteData data;
			SampleInfo info;
			var success = reader.Take(out data, out info);
			if (success != ReturnCode.Ok)
				throw new Exception("Not successful on read: " + success);

			base.OnDataAvailable(entityInterface);

			if (data != null)
			{
				var args = new DataReceivedArgs
				{
					Data = new ArraySegment<byte>(data.Bytes, 0, data.Count),
					SessionID = info.InstanceHandle
				};
				Received.Invoke(this, args);
			}
		}
		private void OnMessageReceived(object sender, MessageEventArgs e)
		{
			var args = new DataReceivedArgs { Data = new ArraySegment<byte>(e.RawData, 0, e.RawData.Length) };
			Received.Invoke(this, args);
		}
Esempio n. 19
0
		public override void on_data_available(DataReader reader)
		{
			var bytes = new Bytes();
			var info = new SampleInfo();

			reader.take_next_sample_untyped(bytes, info);

			if (bytes.value != null)
			{
				var args = new DataReceivedArgs
				{
					Data = new ArraySegment<byte>(bytes.value, bytes.offset, bytes.length),
					SessionID = info.instance_handle
				};
				Received.Invoke(this, args);
			}
		}
        private async Task RunReadLoop(IDictionary <string, object> websocketContext)
        {
            // can't get these before the accept call, apparently
            var sendAsync    = (WebSocketSendAsync)websocketContext["websocket.SendAsync"];
            var receiveAsync = (WebSocketReceiveAsync)websocketContext["websocket.ReceiveAsync"];
            var closeAsync   = (WebSocketCloseAsync)websocketContext["websocket.CloseAsync"];

            var buffer  = new byte[8192];
            var segment = new ArraySegment <byte>(buffer, 0, buffer.Length);

            var stream = new MemoryStream();

            // make sure thread username gets propagated to the handler thread
            // should we have a connectionID -- some random number here? maybe it's in the context?
            // connected and disconnected need try/catch
            // disconnected may need the reason
            do
            {
                try
                {
                    WebSocketReceiveTuple received;
                    stream.SetLength(0);
                    do
                    {
                        received = await receiveAsync.Invoke(segment, CancellationToken);

                        stream.Write(segment.Array, segment.Offset, received.Item3);
                    } while (!received.Item2 && !CancellationToken.IsCancellationRequested);

                    if (CancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    var isClosed = (received.Item1 & CLOSE_OP) > 0;
                    if (isClosed)
                    {
                        break;
                    }

                    var isUTF8       = (received.Item1 & TEXT_OP) > 0;
                    var isCompressed = (received.Item1 & 0x40) > 0;

                    var args = new DataReceivedArgs {
                        SessionID = sendAsync
                    };
                    if (isCompressed)
                    {
                        stream.Position = 0;
                        var array = Decompress(stream);
                        args.Data = new ArraySegment <byte>(array, 0, array.Length);
                    }
                    else
                    {
                        args.Data = new ArraySegment <byte>(stream.GetBuffer(), 0, (int)stream.Length);
                    }

                    Received.Invoke(this, args);
                }
                catch (TaskCanceledException)
                {
                    closeAsync.Invoke(0, "Cancellation Token Triggered", CancellationToken.None);
                    break;
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    if (IsFatalSocketException(ex))
                    {
                        throw;
                    }
                    break;
                }
            }while (true);
            stream.Dispose();
        }