Verification of user's existence in chat script

后端 未结 3 1677
一个人的身影
一个人的身影 2020-12-18 13:36

When ever user leaves chat page (Either by logging out or just by simple closing the browser window). Chat script instantly detects that user left and show offline sign. Thi

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 14:17

    As promised, here are some classes used in implementing long-polling. There are basically 6 classes (see below). Some of these classes may end-up being unneeded for YOUR purposes, but they made sense for mine. These have "mostly" been sanitized for you.

    1. Controller: Processes actions required to create a valid response (db operations etc.)
    2. Processor: Manages asynch communication with the web page (itself)
    3. IAsynchProcessor: The service processes instances that implement this interface
    4. Sevice: Processes request objects that implement IAsynchProcessor
    5. Request: The IAsynchProcessor wrapper containing your response (object)
    6. Response: Contains custom objects or fields

    If you need help with the JavaScript or HTML add-in a comment below...I will write something for you.

    HTTP HANDLERS:

    using System;
    using System.Configuration;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Web.SessionState;
    
    namespace Concept.LongPolling.Handlers
    {
        /// 
        /// Summary description for Controller
        /// 
        public class Controller : IHttpHandler, IReadOnlySessionState
        {
            #region CONSTRUCTORS
            #endregion
    
            #region PROPERTIES
    
            /// Gets a Boolean value indicating that another request can use the current instance of the DefaultHttpHandler class.
            /// Returning true makes the same AsyncHttpHandler object be used for all requests.
            /// Returning false here makes ASP.Net create object per request.
            public bool IsReusable { get { return true; } }
    
            #endregion
    
            #region METHODS
    
            /// Enables synchronous processing of HTTP Web requests
            /// An HttpContext object that provides references to the intrinsic server objects
            /// /// This is where you would send commands to the controller that would affect processing in some manner.
            public void ProcessRequest(HttpContext context)
            {
                throw new NotImplementedException();
            }
    
            /// Creates the response object which is serialized back to the client
            /// 
            public static Response CreateResponse(Response response)
            {
                try
                {
                    response.Generate();
                }
                catch (System.Exception ex)
                {
                    response.SessionValid = false;
                }
    
                return response;
            }
    
            #endregion
        }
    }
    
    using System;
    using System.Configuration;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Web.SessionState;
    using Concept.LongPolling.LongPolling;
    
    namespace Concept.LongPolling.Handlers
    {
        /// 
        /// Summary description for Processor
        /// 
        public class Processor : IHttpHandler, IHttpAsyncHandler, IReadOnlySessionState
        {
            #region CONSTRUCTORS
            #endregion
    
            #region PROPERTIES
    
            /// Gets a Boolean value indicating that another request can use the current instance of the DefaultHttpHandler class.
            /// Returning true makes the same AsyncHttpHandler object be used for all requests.
            /// Returning false here makes ASP.Net create object per request.
            public bool IsReusable { get { return false; } }
    
            #endregion
    
            #region METHODS
    
            /// Enables synchronous processing of HTTP Web requests
            /// An HttpContext object that provides references to the intrinsic server objects
            public void ProcessRequest(HttpContext context)
            {
                throw new NotImplementedException();
            }
    
            #region IHttpAsyncHandler Members
    
            /// Enables asynchronous processing of HTTP Web requests
            /// An HttpContext object that provides references to the intrinsic server objects
            /// The method to call when the asynchronous method call is complete. If callback is null, the delegate is not called.
            /// 
            /// Any state data that is needed to process the request.
            public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
            {
                Int32 someValueYouLikeToSendInYourClass = Convert.ToInt32(context.Request["Number"]);
    
                Request request = new Request(cb, context);
                request.Response.Number = someValueYouLikeToSendInYourClass;
    
                Service.Singleton.AddRequest(request);
    
                return request;
            }
    
            /// Provides an end method for an asynchronous process.
            /// An object that contains information about the status of the process.
            public void EndProcessRequest(IAsyncResult result)
            {
                Request request = result as Request;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
    
                request.HttpContext.Response.ContentType = "text/json";
                request.HttpContext.Response.Write(serializer.Serialize(request.Response));
                request.HttpContext.Response.End();
            }
    
            #endregion
    
            #endregion
        }
    }
    

    SUPPORTING CLASSES:

    using System;
    using System.Runtime.InteropServices;
    
    namespace Concept.LongPolling.LongPolling
    {
        /// Represents the executable instance of an asynchronous operation.
        [ComVisible(true)]
        public interface IAsynchProcessor : IAsyncResult
        {
            /// 
            /// Gets a value that indicates whether the operation completed sucessfully.
            /// 
            /// true if the operation completed sucessfully; otherwise, false.
            bool ProcessRequest();
        }
    }
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Threading;
    
    namespace Concept.LongPolling.LongPolling
    {
        public class Service
        {
            #region CONSTRUCTORS
    
            private Service()
            {
                requests = new List();
                backgroundThread = new Thread(new ThreadStart(MainLoop));
                backgroundThread.IsBackground = true;
                backgroundThread.Start();
            }
    
            #endregion
    
            #region PROPERTIES
    
            static readonly object _padlock = new object();
    
            private static Service singleton;
            private Thread backgroundThread;
            private List requests;
    
            public static Service Singleton
            {
                get
                {
                    lock (_padlock)
                    {
                        if (_singleton == null)
                            _singleton = new Service();
                        return _singleton;
                    }
                }
            }
    
            #endregion
    
            #region METHODS
    
            private void MainLoop()
            {
                while (true)
                {
                    foreach (IAsynchProcessor request in requests.ToArray())
                    {
                        if (request.ProcessRequest())
                            requests.Remove(request);
                    }
                    Thread.Sleep(500);
                }
            }
    
            public void AddRequest(IAsynchProcessor request)
            {
                requests.Add(request);
            }
    
            #endregion
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Concept.LongPolling.Business;
    using System.Data;
    
    namespace Concept.LongPolling.Handlers
    {
        public class Response
        {
            #region CONSTRUCTORS
    
            public Response()
            {
                SessionValid = true;
                Exception = String.Empty;
            }
    
            #endregion
    
            #region PROPERTIES
    
            public const int TimeOffset = 120;
    
            public Int32 Number { get; set; }
            public bool SessionValid { get; set; }
            public String Exception { get; set; }
    
            #endregion
    
            #region METHODS
    
            public void Generate()
            {
                // do some desired operation
                Number += 1;
            }
    
            #endregion
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Concept.LongPolling.LongPolling;
    
    namespace Concept.LongPolling.Handlers
    {
        public class Request : IAsynchProcessor
        {
            #region CONSTRUCTORS
    
            public Request(AsyncCallback callback, HttpContext context)
            {
                asyncCallback = callback;
                httpContext = context;
                createdTime = DateTime.Now;
    
                Response = new Response();
            }
    
            #endregion
    
            #region PROPERTIES
    
            public const int TimeoutSeconds = 15;
    
            private AsyncCallback asyncCallback;
            private HttpContext httpContext;
            private DateTime createdTime;
    
            public bool TimedOut
            {
                get
                {
                    return ((DateTime.Now - createdTime).TotalSeconds >= TimeoutSeconds);
                }
            }
    
            public Response Response { get; set; }
    
            #region IAsyncResult Members
    
            public HttpContext HttpContext
            {
                get
                {
                    return httpContext;
                }
            }
            public object AsyncState { get; set; }
    
            System.Threading.WaitHandle IAsyncResult.AsyncWaitHandle
            {
                get { throw new NotImplementedException(); }
            }
    
            bool IAsyncResult.CompletedSynchronously
            {
                get { return false; }
            }
    
            public bool IsCompleted
            {
                get { return isCompleted; }
                set
                {
                    if (!value) return;
    
                    this.isCompleted = true;
                    asyncCallback(this);
                }
            }
            bool isCompleted = false;
    
            #endregion
    
            #endregion
    
            #region METHODS
    
            public bool ProcessRequest()
            {
                this.Response = Controller.CreateResponse(this.Response);
                this.IsCompleted = true;
    
                return this.IsCompleted;
            }
    
            #endregion
        }
    }
    

提交回复
热议问题