Esempio n. 1
0
    private async System.Threading.Tasks.Task <Response> ReceiveMessage()
    {
        // Receive one web socket message
        System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> > segments = new System.Collections.Generic.List <System.Collections.Generic.IEnumerable <byte> >();

        try
        {
            while (true)
            {
                byte[] buffer  = new byte[4096];
                var    segment = new System.ArraySegment <byte>(buffer, 0, buffer.Length);
                System.Net.WebSockets.WebSocketReceiveResult rcvResult = await ws.ReceiveAsync(segment, stopServerTokenSource.Token);

                // Accumulate the byte arrays in a list, we will join them later
                segments.Add(segment.Skip(segment.Offset).Take(rcvResult.Count));

                if (rcvResult.EndOfMessage)
                {
                    break;
                }
            }
        }
        catch (System.Net.WebSockets.WebSocketException e)
        {
            throw e.InnerException;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error receiving response from server.");
        }

        try
        {
            byte[] bytes = segments.SelectMany(t => t).ToArray <byte>();
            string msg   = System.Text.Encoding.UTF8.GetString(bytes);
            return(Parse(msg));
        }
        catch (ErrorException e)
        {
            // Dispatch already built error
            throw e;
        }
        catch (System.Exception)
        {
            throw new ErrorException("Error while parsing response from server.");
        }
    }
 /// <summary>
 ///     Creates a new array segment by taking a number of elements from the end of this array segment.
 /// </summary>
 /// <typeparam name="T">The type of elements contained in the array.</typeparam>
 /// <param name="segment">The array segment.</param>
 /// <param name="count">
 ///     The number of elements in the new array segment. This must be in the range
 ///     <c>[0, <paramref name="segment" />.Count]</c>.
 /// </param>
 /// <returns>The new array segment.</returns>
 public static ArraySegment <T> TakeLast <T>(this ArraySegment <T> segment, int count)
 {
     return(segment.Skip(segment.Count - count));
 }