示例#1
0
        /// <summary>
        /// When the user makes a GET request, 
        /// we’ll create a new HttpResponseMessage using PushStreamContent object 
        /// and text/event-stream content type. 
        /// PushStreamContent takes an Action&lt;Stream, HttpContentHeaders, TransportContext&gt; onStreamAvailable parameter in the constructor, and that in turn allows us to manipulate the response stream.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public HttpResponseMessage Get()
        {
            try
            {
                var json = Server.UrlDecode(Request.QueryString[null]);
                Parcel m = JsonConvert.DeserializeObject<Parcel>(json);
                StreamClient client = ws.ClientByID(m.client) as StreamClient;
                if (client == null)
                {
                    client = new StreamClient() { Response = Response, clientID = m.client };
                    //client.SessionID = HttpContext.Session.SessionID;
                    ws.AddClient(client);
                    Response.ContentType = "text/event-stream";
                    Response.Headers.Add("Connection", "Keep-Alive");
                }
                else
                {
                    client.Response = Response;
                }

                do
                {
                    if (!ws.SendOne(client).Result)
                    {
                        return null;
                    };
                    Response.Flush();
                    Thread.Sleep(200);
                } while (true);
            }
            catch (Exception ex)
            {

            }
            return null;
        }