日期:2014-05-18  浏览次数:20719 次

急,求助,C# socket服务端接收并解析客户端发送的http请求
C# code

IPHostEntry gist = Dns.GetHostByName("localhost");
                    IPAddress ip = gist.AddressList[0];
                    IPEndPoint IPEP = new IPEndPoint(ip, 6666);
                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sock.Bind(IPEP);
                    sock.Listen(10);
                    _logger.Log("开启服务,开始侦听:" + IPEP.Port, Category.Info, Priority.Medium);
                    int sum = 0;
                    while (true)
                    {
                        // 开始监听,这个方法会阻塞线程的执行,直到接受到一个客户端的连接请求
                        Socket client = sock.Accept();
                        // 输出客户端的地址
                        _logger.Log(client.RemoteEndPoint.ToString(), Category.Info, Priority.Medium);
                        // 准备读取客户端请求的数据,读取的数据将保存在一个数组中
                        byte[] buffer = new byte[4096];
                        // 接受数据
                        int length = client.Receive(buffer, 4096, SocketFlags.None);
                        // 将请求的数据翻译为 UTF-8
                        System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                        string requestString = utf8.GetString(buffer, 0, length);
                        // 显示请求的内容
                        Console.WriteLine(requestString);
                    }
                    // 关闭服务器
                    sock.Close();


这是我服务端的侦听代码,用于接收客户端发送的http请求,requestString接收的字符串是:
POST /?param=sfds HTTP/1.1
Accept: */*
Content-Type: application/x-www-form-urlencoded
Host: 127.0.0.1:6666
Content-Length: 12
Expect: 100-continue
Connection: Keep-Alive
要怎么解析出包头param参数的值?求助各位大大啦!~请各位大大给我代码参考一下

------解决方案--------------------
帮你顶吧,想不出来什么办法。
以前接受到的字符串都是AAA:aaa&BBB:bbb 这样的,你的两个参数之间都没分割吗?
------解决方案--------------------
既然你要做Http解析,就要理解Http协议。比如先看wiki的超文本传输协议:

http://zh.wikipedia.org/wiki/%E8%B6%85%E6%96%87%E6%9C%AC%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE
------解决方案--------------------
探讨
我只要能获取到包头的param参数值就行了,不用解析得很透彻