C # Async Webserver - how to send data to a client

It could be a piece of cake for any experienced C # developer.

Here you see an example of an asynchronous web server

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SimpleServer
{
    class Program
    {
        public static void ReceiveCallback(IAsyncResult AsyncCall)
        {            
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] message = encoding.GetBytes("I am a little busy, come back later!");            
            Socket listener = (Socket)AsyncCall.AsyncState;
            Socket client = listener.EndAccept(AsyncCall);
            Console.WriteLine("Received Connection from {0}", client.RemoteEndPoint);
            client.Send(message);
            Console.WriteLine("Ending the connection");
            client.Close();
            listener.BeginAccept(new AsyncCallback(ReceiveCallback), listener);
        }

    public static void Main()
    {
        try
        {
            IPAddress localAddress = IPAddress.Parse("127.0.0.1");
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 8080);
            listenSocket.Bind(ipEndpoint);
            listenSocket.Listen(1);
            listenSocket.BeginAccept(new AsyncCallback(ReceiveCallback), listenSocket);
            while (true)
            {                    
                Console.WriteLine("Busy Waiting....");
                Thread.Sleep(2000);
            }                
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught Exception: {0}", e.ToString());
        }
    }
}

I downloaded it from the Internet in order to have a basic model for working.

Basically, what I need to do is run this web server as a process on the computer. He will listen to 8080 all the time, and when the client computer sends a request, this server will process some data and send the result as a string.

I created a small project with this code (which is functional as it is), but when it executes the line

client.Send(message);

all i get is a browser error or at most a blank page

I suspect that I need to define HTTP headers for sending with a message, but I searched the Internet for this with no luck

Who wants to help?

Thank!

+5
1

-

HTTP/1.1 200 OK
Server: My Little Server
Content-Length: [Size of the Message here]
Content-Language: en
Content-Type: text/html
Connection: close

[Message]

, .

Edit:

:

    public static void SendHeader(string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
    {
        String sBuffer = "";
        // if Mime type is not provided set default to text/html
        if (sMIMEHeader.Length == 0)
        {
            sMIMEHeader = "text/html";  // Default Mime Type is text/html
        }
        sBuffer = sBuffer + "HTTP/1.1" + sStatusCode + "\r\n";
        sBuffer = sBuffer + "Server: cx1193719-b\r\n";
        sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
        sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
        sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";
        Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);
        mySocket.Send(Encoding.ASCII.GetBytes(sBuffer),Encoding.ASCII.GetBytes(sBuffer).Length, 0);
        Console.WriteLine("Total Bytes : " + iTotBytes.ToString());
    }

Main() - Method

Byte[] message = encoding.GetBytes("I am a little busy, come back later!");

string messageString = "I am a little busy, come back later!";
Byte[] message = encoding.GetBytes(messageString);

// Unicode char may have size more than 1 byte so we should use message.Length instead of messageString.Length
SendHeader("text/html", message.Length, "202 OK", ref client);

client.Send(message);

.

+4

All Articles