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

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

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

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

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

client.Send(message);

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

我怀疑我需要定义与(消息)一起发送的 HTTP header ,但我一直在网上搜索这个但没有成功

有人愿意帮忙吗?

谢谢!

最佳答案

你需要这样的东西

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]

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

编辑:

你可以使用这个方法:

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

就这些。

关于C# 异步 Web 服务器 - 如何将数据发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5247732/

相关文章:

c# - 组合框的默认文本

C# 拖放 - 使用基类的 e.Data.GetData

Android 2.2 与 2.3 - HTTP header 中的 soapaction 与 SOAPAction

php - 内容类型和 json_encode() 值

c - 无法使用c中的套接字发送大文件

JQuery GET 请求 TCP 套接字服务器

c# - 根据 C# 中的约定创建文件夹结构的最佳方法是什么

c# - 如何获取 ISubscriber 连接的客户端 ID?

javascript - 无法使用 http-server wiki 示例

Tomcat 6 禁用 JSESSIONID