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

C#

 
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 
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 
I Have found what the problem was.
It was not so much as there was data in the connected socket I did not read but new connection I was not serving.

Having it in multiple threads to accept the connection didn't really help.
I was only accepting once and recreating a task was probably not fast enough.
Having it in a loop works well:
while (true)
{
  var connectedSocket = mMainSocket.Accept();
  Task.Factory.StartNew(delegate
  {
    ServeConnection(connectedSocket, l);
  });
}



I copy the whole source, for all the times I found a 2 years old forum question that finishes by 'I found the solution never mind!' and I wish I could read it:

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: 1, 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 < 10; j++)
                {
                    for (int i = 0; i < 10; 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
                {
                    while (true)
                    {
                        var connectedSocket = mMainSocket.Accept();
                        connectedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
                        Console.WriteLine("L{0} is Accepted", l);
                        var task2 = Task.Factory.StartNew(delegate
                        {
                            ServeConnection(connectedSocket, 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 ServeConnection(Socket connectedSocket, int l)
            {
                int requestNo = 0;

                try
                {
                    const int BUFFER_SIZE = 4096;
                    var requestBuffer = new Byte[BUFFER_SIZE];
                    int readIndex = 0;
                    while (true)
                    {
                        SocketError socketError;
                        var read = connectedSocket.Receive(requestBuffer, readIndex, requestBuffer.Length - readIndex, SocketFlags.None, out socketError);
                        var requestString = Encoding.ASCII.GetString(requestBuffer, 0, read);
                        Console.WriteLine("{0} read {1} ({2})", l, read, requestString.Substring(0, Math.Min(20, requestString.Length)));

                        if (read == 0) return;
                        int pos = IndexOfCrLfCrLf(requestBuffer, read);
                        readIndex += read;
                        if (pos < 0)
                        {
                            pos = 0;
                        }
                        else
                        {
                            while (pos >= 0)
                            {
                                if (pos == 0)
                                    break;
                                requestNo++;
                                //Console.WriteLine("{0} is processing request #{1}", l, requestNo);
                                string response = "Hello";
                                string contentType = "text/plain";
                                Byte[] responseArray = null;
                                requestString = Encoding.UTF8.GetString(requestBuffer, 0, pos);

                                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);
                                connectedSocket.Send(headerArray, headerArray.Length, SocketFlags.None);
                                connectedSocket.Send(responseArray, responseArray.Length, SocketFlags.None);
                                if (mUseHttp11 == false)
                                {
                                    connectedSocket.Close();
                                    return;
                                }
                                pos += 4; // CR LF CR LF
                                readIndex -= pos;
                                if (readIndex > 0)
                                {
                                    Array.Copy(requestBuffer, pos, requestBuffer, 0, readIndex);
                                    pos = IndexOfCrLfCrLf(requestBuffer, readIndex);
                                }
                                else
                                {
                                    readIndex = 0;
                                    pos = -1;
                                }
                            }
                        }
                    }
                    Console.WriteLine("Request complete");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception " + ex.Message);
                }
                finally
                {
                    connectedSocket.Close();
                }
            }

            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;
            }
        }

    }
}

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 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eder Sa22-Mar-11 11:26
Eder Sa22-Mar-11 11:26 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eddy Vluggen22-Mar-11 22:19
professionalEddy Vluggen22-Mar-11 22:19 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eder Sa23-Mar-11 6:19
Eder Sa23-Mar-11 6:19 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Pete O'Hanlon23-Mar-11 6:45
mvePete O'Hanlon23-Mar-11 6:45 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Eder Sa23-Mar-11 6:52
Eder Sa23-Mar-11 6:52 
GeneralRe: How to improve listbox databind in WIndows Mobile 6 Pin
Pete O'Hanlon23-Mar-11 23:07
mvePete O'Hanlon23-Mar-11 23:07 

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.