动态获取页面参数内容

本文章主要内容为动态的获取页面内容,在地址栏后面输入参数进行相加,最终将结果返回给用户,此程序运行后出现的错误无需理会,只需将程序运行起来就行了,细节问题后续会讲,如:

http://i.cnblogs.com/add?i=1&j=2,?前面的为处理程序路径,?后面的为请求的参数,以&分割多个参数,注意这是HTTP协议格式,一种规范,一种标准

static void Main(string[] args)
{
    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
    serverSocket.Listen(10);
    while (true)
    {
        Console.WriteLine("等着请求");
        Socket socket = serverSocket.Accept();
        Console.WriteLine("来了请求了");
        string firstline;
        using (NetworkStream stream = new NetworkStream(socket))
        using (StreamReader reader = new StreamReader(stream))
        {
            firstline = reader.ReadLine();//读取GET /1.html HTTP/1.1
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
                if (line.Length <= 0)
                {
                    break;
                }
            }
        }

        string[] strs = firstline.Split(' ');
        string url = strs[1];//1.html
        string[] strs2 = url.Split('?');//add?i=1&j=2
        string fileAction = strs[0];//add
        string qs = strs2[1];
        Dictionary<string, string> dic = ParseQureyString(qs);
        int i = Convert.ToInt32(dic["i"]);
        int j = Convert.ToInt32(dic["j"]);

        using (NetworkStream stream = new NetworkStream(socket))
        using (StreamWriter write = new StreamWriter(stream))
        {
            write.WriteLine("HTTP/1.1 200 OK");
            write.WriteLine();
            write.WriteLine(i + j);
        }
        socket.Disconnect(false);
    }
}
/// <summary>
/// 把i=1&j=2转换为一个Dictionary
/// </summary>
/// <param name="qs"></param>
/// <returns></returns>
private static Dictionary<string, string> ParseQureyString(string qs)
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    string[] strs = qs.Split('&');
    foreach (string str in strs)
    {
        string[] kv = str.Split('=');
        string name = kv[0];
        string value = kv[1];
        dic.Add(name, value);
    }
    return dic;
}

 

判断用户名和密码,把结果返回给客户端

/login?username=admin&password=123 

在上面的代码中,将获取到的dic取出来即可

string username = dic["username"];
string password = dic["password"];

posted @ 2015-07-19 16:22  黄者之风  阅读(1130)  评论(0编辑  收藏  举报