Click here to Skip to main content
15,895,799 members
Articles / Programming Languages / C#

C# WebServer Using Sockets

Rate me:
Please Sign up or sign in to vote.
5.00/5 (27 votes)
23 Jan 2014CPOL7 min read 103.9K   9.9K   161  
How to make a simple web server which supports GZIP compression, applications, and sessions.
using System;
using AsyncSocketSample;
using ServerCommonLibrary;
using System.Net;

namespace ComunicationLayer
{
    /// <summary>
    /// This class abastracts the socket engine implementation ,exposing IChannelOutput interface to send data in output (to browser/client)
    /// and using IServerBase interface to deal the input requests.    
    /// </summary>
    public class SocketComunicator : IDisposable, IChannelOutput
    {

        //### socket engine component
        Server sockengine;

        //### server input handler
        IServiceBase serviceInterface;

        public SocketComunicator()
        {
            this.sockengine = new Server(10, 2048);
            ManageSocketEngineEvents(true);
            sockengine.Init();
        }


        /// <summary>
        /// Start listening at the specified port
        /// </summary>
        /// <param name="listenPort"></param>
        public void StartListen(int port)
        {
            this.sockengine.Start(new IPEndPoint(IPAddress.Parse("0.0.0.0"), port));
        }

        /// <summary>
        /// Set the service interface
        /// </summary>
        /// <param name="wb"></param>
        public void SetServiceHandler(IServiceBase wb)
        {
            this.serviceInterface = wb;
        }

        /// <summary>
        /// New message incoming from the NET
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="dataRef"></param>
        void Socket_OnNewDataReceived(object sender, SocketConnection e, byte[] dataRef)
        {
            if (this.serviceInterface != null)
                this.serviceInterface.ParseNewRequest(new RawRequest() { Connection = e, RawData = dataRef });
        }



        protected void ManageSocketEngineEvents(bool add)
        {
            if (add) sockengine.OnNewDataReceived += new Server.SocketConnectionEventHandler(Socket_OnNewDataReceived);
            else sockengine.OnNewDataReceived -= (Socket_OnNewDataReceived);

        }

        /// <summary>
        /// Send a response through the socket
        /// </summary>
        /// <param name="e"></param>
        public void SendResponse(RawResponse e)
        {
            try
            {
                switch (e.Action)
                {
                    case ResponseAction.Disconnect:
                        e.Request.Connection.Socket.Disconnect(false);
                        break;
                    case ResponseAction.Send:
                        int sent = e.Request.Connection.Socket.Send(e.ElaborateData());
                        break;
                    case ResponseAction.Skip:
                        break;
                }
            }
            catch
            {

            }
        }
        
        public void Dispose()
        {
            if (sockengine != null)
            {
                //It's important remove handlers
                ManageSocketEngineEvents(false);
                //sockengine.Dispose(); MS in his example never implement the dispose, bad habit!!.
                sockengine = null;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
Alberto Biafelli,
Software Developer

Comments and Discussions