Click here to Skip to main content
15,889,281 members
Home / Discussions / C#
   

C#

 
AnswerRe: New Version Update Pin
RobCroll23-Mar-11 23:54
RobCroll23-Mar-11 23:54 
AnswerRe: New Version Update Pin
PIEBALDconsult26-Mar-11 5:47
mvePIEBALDconsult26-Mar-11 5:47 
QuestionHow do I defined property in C#? Pin
baisak23-Mar-11 19:03
baisak23-Mar-11 19:03 
AnswerRe: How do I defined property in C#? Pin
JF201523-Mar-11 19:05
JF201523-Mar-11 19:05 
AnswerRe: How do I defined property in C#? Pin
Pravin Patil, Mumbai23-Mar-11 22:18
Pravin Patil, Mumbai23-Mar-11 22:18 
AnswerRe: How do I defined property in C#? Pin
Nitheesh George24-Mar-11 2:50
Nitheesh George24-Mar-11 2:50 
AnswerRe: How do I defined property in C#? Pin
fjdiewornncalwe24-Mar-11 4:29
professionalfjdiewornncalwe24-Mar-11 4:29 
QuestionMiniHttpServer Pin
Pascal Ganaye23-Mar-11 16:02
Pascal Ganaye23-Mar-11 16:02 
I am writing a socket server and I have some trouble which I did expose through the program below.
If your run this program (this is a console program).
You'll find it open a web browser on a local address and shows 256 small pictures.
For the purpose of this test the pictures are actually quite large but are shown in small.

This is the complete C# 4.0 source, I encourage you to try it.

It really render really fast considering the time I have put into this.
But if you refresh your page you'll see that some of the pictures do not appear properly.
Anyone knows the reason for this.

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MiniHttpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpServer.Test();
        }

        class HttpServer
        {
            internal static Byte[] mIndex;
            internal static Byte[] mPic;
            Socket mMainSocket;
            bool mUseHttp11;

            static HttpServer()
            {
                mIndex = GetIndex();
                mPic = GetCirclePicture();
            }

            public static void Test()
            {
                var httpServer = new HttpServer();
                httpServer.StartServer(port: 3005, nbListeners: 4, useHttp11: true);
                
                Process.Start("http://localhost:3005/");
                Console.WriteLine("Press a key to exit");
                Console.ReadKey(intercept: true);
                httpServer.Stop();
            }

            private static Byte[] GetIndex()
            {
                StringBuilder html = new StringBuilder();
                html.AppendLine("<html><body>");
                html.AppendLine("<h1>Pics</h1>");
                int k = 0;
                for (int j = 0; j < 16; j++)
                {
                    for (int i = 0; i < 16; i++)
                    {
                        html.AppendLine("<img width='16' height='16' src='p" + (k++) + ".png'>");
                    }
                    html.AppendLine("<br/>");
                }
                return Encoding.UTF8.GetBytes(html.ToString());
            }

            private static Byte[] GetCirclePicture()
            {
                var bmp = new Bitmap(256, 256);
                using (var g = Graphics.FromImage(bmp))
                {
                    for (int i = 0; i < 128; i++)
                    {
                        g.FillEllipse(new SolidBrush(Color.FromArgb(i, i, 255)), i, i, 255 - 2 * i, 255 - 2 * i);
                    }
                }
                var mem = new MemoryStream();
                bmp.Save(mem, ImageFormat.Png);
                return mem.ToArray();
            }

            public void StartServer(int port, int nbListeners, bool useHttp11)
            {
                mUseHttp11 = useHttp11;
                var webAddress = new IPEndPoint(IPAddress.Loopback, port);
                try
                {
                    mMainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    mMainSocket.Bind(webAddress);
                    mMainSocket.Listen(255);

                    for (int i = 0; i < nbListeners; i++)
                    {
                        CreateListener(i);
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            private void CreateListener(int l)
            {
                var newTask = Task.Factory.StartNew(delegate
                {
                    var requestSocket = mMainSocket.Accept();
                    //requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
                    Console.WriteLine("L{0} is Accepted", l);
                    ProcessRequest(requestSocket, l);
                    Console.WriteLine("L{0} is dying gracefully", l);
                }).ContinueWith(delegate
                {
                    if (mMainSocket.IsBound)
                    {
                        Console.WriteLine("L{0} is really dead and is trying to resurrect", l);
                        CreateListener(l);
                    }
                    else
                    {
                        Console.WriteLine("L{0} is really dead and burried", l);
                    }
                });
            }

            private void ProcessRequest(Socket requestSocket, int l)
            {
                try
                {
                    const int BUFFER_SIZE = 4096;
                    var requestBuffer = new Byte[BUFFER_SIZE];
                    int requestPos = 0;
                    int requestNo = 0;
                    while (requestPos < BUFFER_SIZE)
                    {
                        SocketError socketError;
                        var read = requestSocket.Receive(requestBuffer, requestPos, requestBuffer.Length - requestPos, SocketFlags.None, out socketError);

                        if (socketError == SocketError.TimedOut)
                        {
                            continue;
                        }
                        // if (socketError != SocketError.Success) { }
                        if (read == 0) continue;
                        var requestString = Encoding.ASCII.GetString(requestBuffer, 0, read);
                        var sr = new StringReader(requestString);
                        var line = sr.ReadLine();
                        var request = line;
                        while (line != null && line.Length > 0)
                        {
                            line = sr.ReadLine();
                        }
                        if ((line = sr.ReadToEnd()) != null && line.Length > 0)
                        {
                            Console.WriteLine("Lost:" + line);
                        }
                        int len = requestPos + read;
                        int pos = IndexOfCrLfCrLf(requestBuffer, len);
                        if (pos >= 0)
                        {
                            if (pos == 0)
                                break;
                            requestNo++;
                            Console.WriteLine("{0} is processing request #{1}", l, requestNo);
                            requestPos = 0;
                            string response = "Hello";
                            string contentType = "text/plain";
                            Byte[] responseArray = null;
                            if (requestString.StartsWith("GET / "))
                            {
                                contentType = "text/html";
                                responseArray = mIndex;
                            }
                            else if (requestString.IndexOf(".png") >= 0)
                            {
                                contentType = "image/png";
                                responseArray = mPic;
                            }
                            if (responseArray == null) responseArray = Encoding.UTF8.GetBytes(response);
                            string header =
                                "HTTP/1." + (mUseHttp11 ? '1' : '0') + " 200 OK\r\n"
                                + "Content-Length: " + responseArray.Length + "\r\n"
                                + (mUseHttp11 ? ("Content-Type: " + contentType + "\r\n") : "")
                                + "\r\n";
                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            requestSocket.Send(headerArray, headerArray.Length, SocketFlags.None);
                            requestSocket.Send(responseArray, responseArray.Length, SocketFlags.None);
                            if (mUseHttp11 == false)
                            {
                                requestSocket.Close();
                                break;
                            }
                        }
                        else requestPos = len;
                    }
                    Console.WriteLine("Request complete");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception " + ex.Message);
                }
            }

            private void Nop()
            {

            }

            public void Stop()
            {
                mMainSocket.Close();
            }

            static int IndexOfCrLfCrLf(byte[] requestBuffer, int len)
            {
                for (int i = 0; i <= (len - 4); i++)
                {
                    if (requestBuffer[i] == '\r'
                        && requestBuffer[i + 1] == '\n'
                        && requestBuffer[i + 2] == '\r'
                        && requestBuffer[i + 3] == '\n')
                    {
                        return i;
                    }
                }
                return -1;
            }
        }

    }
}

AnswerRe: MiniHttpServer Pin
PIEBALDconsult23-Mar-11 16:06
mvePIEBALDconsult23-Mar-11 16:06 
AnswerRe: MiniHttpServer [modified] Pin
Dave Kreskowiak23-Mar-11 17:58
mveDave Kreskowiak23-Mar-11 17:58 
GeneralRe: MiniHttpServer Pin
DaveyM6924-Mar-11 0:18
professionalDaveyM6924-Mar-11 0:18 
GeneralRe: MiniHttpServer Pin
Dave Kreskowiak24-Mar-11 1:54
mveDave Kreskowiak24-Mar-11 1:54 
AnswerRe: MiniHttpServer Pin
BobJanova24-Mar-11 3:13
BobJanova24-Mar-11 3:13 
AnswerRe: MiniHttpServer -- ANSWERED Pin
Pascal Ganaye26-Mar-11 8:19
Pascal Ganaye26-Mar-11 8:19 
QuestionWindows service setup custom action Error 1001 System.BadImageFormatException Pin
Chesnokov Yuriy23-Mar-11 9:30
professionalChesnokov Yuriy23-Mar-11 9:30 
QuestionWriting a Text in StreamWriter such that alignment should be proper for different languages ( like English, Chinise, German...etc). Pin
Piyush Vaishnav23-Mar-11 0:42
Piyush Vaishnav23-Mar-11 0:42 
AnswerRe: Writing a Text in StreamWriter such that alignment should be proper for different languages ( like English, Chinise, German...etc). PinPopular
Luc Pattyn23-Mar-11 1:24
sitebuilderLuc Pattyn23-Mar-11 1:24 
AnswerRe: Writing a Text in StreamWriter such that alignment should be proper for different languages ( like English, Chinise, German...etc). Pin
TheyCallMeMrJames23-Mar-11 3:53
TheyCallMeMrJames23-Mar-11 3:53 
GeneralRe: Writing a Text in StreamWriter such that alignment should be proper for different languages ( like English, Chinise, German...etc). Pin
Piyush Vaishnav23-Mar-11 22:20
Piyush Vaishnav23-Mar-11 22:20 
GeneralRe: Writing a Text in StreamWriter such that alignment should be proper for different languages ( like English, Chinise, German...etc). Pin
TheyCallMeMrJames24-Mar-11 5:51
TheyCallMeMrJames24-Mar-11 5:51 
QuestionHow to improve listbox databind in WIndows Mobile 6 Pin
Eder Sa22-Mar-11 9:33
Eder Sa22-Mar-11 9:33 
AnswerRe: How to improve listbox databind in WIndows Mobile 6 Pin
Not Active22-Mar-11 9:55
mentorNot Active22-Mar-11 9:55 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eder Sa22-Mar-11 10:10
Eder Sa22-Mar-11 10:10 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Not Active22-Mar-11 10:36
mentorNot Active22-Mar-11 10:36 
AnswerRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eddy Vluggen22-Mar-11 10:41
professionalEddy Vluggen22-Mar-11 10:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.