【问题标题】:C# Async Webserver - how to send data to clientC# Async Webserver - 如何向客户端发送数据
【发布时间】:2011-03-09 15:07:14
【问题描述】:

这对于任何有经验的 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 标头,但我一直在网上搜索这个,但没有运气

有人愿意帮忙吗?

谢谢!

【问题讨论】:

    标签: c# http-headers webserver asyncsocket


    【解决方案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]
    

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

    编辑:

    你可以使用这个方法:

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

    就是这样。

    【讨论】:

    • 感谢您的提示!我一直在谷歌搜索,但我找不到生成 HTTP 标头的方法……你能给我一个链接或基于我粘贴的代码的示例吗?再次感谢!
    • 正在处理它。有趣的事实:我复制了你的代码,编译它,它可以工作:-D
    • 哇,太好了!另一个有趣的事实:在我正在进行的另一个测试项目中,我有一个与此类似的方法,并且几乎完全按照您在此处描述的那样做到了这一点,并且它非常有效......一百万谢谢......我想我仍然不能分配点或类似的东西,但你应该知道,如果可以的话,我很乐意给你一些……谢谢!
    • 哈,哈!!这就是我所说的双赢关系... ;)
    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 2017-05-07
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2015-09-23
    • 2016-02-23
    • 2022-07-08
    相关资源
    最近更新 更多