C#异步Web服务器 - 如何将数据发送到客户端

时间:2011-03-09 15:07:14

标签: c# http-headers webserver asyncsocket

对于任何有经验的C#开发人员来说,这可能是小菜一碟

您在此处看到的是异步网络服务器示例

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

我是从网上下载的,以便有一个基本模型可供使用。

基本上我需要做的是将此网络服务器作为计算机中的进程运行。它将一直监听8080,当客户端计算机发送请求时,该服务器将处理一些数据并将结果作为字符串发回。

我使用此代码创建了一个小项目(按原样运行),但是当它执行行

client.Send(message);

我得到的只是浏览器中的错误,或者最多是一个空白页

我怀疑我需要定义要与(消息)一起发送的HTTP标头,但我一直在网上搜索没有运气

是谁愿意帮忙?

谢谢!

1 个答案:

答案 0 :(得分:4)

你需要这样的东西

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]

如果您发送此数据空洞块,它应该可以正常工作。

修改

您可以使用此方法:

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

就是这样。