C# HttpListener建立Http服务器并使用Silverlight来发送POST请求的疑问

.Net技术 码拜 8年前 (2016-09-16) 2879次浏览
本人首先使用C#Httplistener创建了一个Http服务器,然后在Silverlight端来发送POST请求,向服务器发送一个字符串,但是服务器这边接收到的请求始终是GET而且没有数据,不知问题出在哪里,求各位指点。
服务器代码

    class HttpServer
    {
        //开始监听服务
        public void StartHttpServer()
        {
            try
            {
                Console.WriteLine("检查操作系统:" + DateTime.Now.ToString());
                
                if (!HttpListener.IsSupported)
                {
                    Console.WriteLine("无法在当前系统上运行服务(Windows XP SP2 or Server 2003)。" + DateTime.Now.ToString());
                    return;
                }
                //需要监听的URL前缀
                string svrName = string.Format("http://127.0.0.1:2222/");
                HttpListener listener = new HttpListener();
                //匿名访问
                listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                listener.Prefixes.Add(svrName);
                //开始监听
                listener.Start();
                #region
                //int maxThread;
                //int portThread;
                //int minThread;
                //int minPortThread;
                ////线程池最大线程和最小线程空闲数
                //ThreadPool.GetMaxThreads(out maxThread,out portThread);
                //ThreadPool.GetMinThreads(out minThread,out minPortThread);
                //Console.WriteLine("最大线程数:{0}",maxThread);
                //Console.WriteLine("最小线程空闲数:{0}", minPortThread);
                #endregion
                //异步处理请求
                listener.BeginGetContext(new AsyncCallback(GetContextCallBack), listener);
                Console.WriteLine("{0}", "服务启动成功。");
                Console.WriteLine("{0}", svrName);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        private void GetContextCallBack(IAsyncResult ar)
        {
            try
            {
                HttpListener listener = ar.AsyncState as HttpListener;
                ClientUser userInfo;
                
                HttpListenerContext context = listener.EndGetContext(ar);
                
                listener.BeginGetContext(new AsyncCallback(GetContextCallBack),listener);
                if (context.Request.HttpMethod.ToLower().ToString() == "get")
                {
                    using (Stream inputStream = context.Request.InputStream)
                    {
                        byte[] b = new byte[1024];
                        int jL = inputStream.Read(b, 0, b.Length);
                        string json = Encoding.UTF8.GetString(b,0,jL);
                    }
                    Console.WriteLine("GET Request...");
                    
                    //就不返回数据了
                }
                else if (context.Request.HttpMethod.ToLower().ToString() == "post")
                {
                    //读取客户端发送过来的数据
                    using (Stream inputStream = context.Request.InputStream)
                    {
                        byte[] buffer = new byte[1024];
                        //读取用户发送过来的正文
                        int jsonLength = inputStream.Read(buffer, 0, buffer.Length);
                        if (jsonLength <= 0) return;
                        //将其转为字符串
                        string json = Encoding.UTF8.GetString(buffer, 0, jsonLength);
                        userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientUser>(json);
                        //验证数据库
                        
                        //返回登录结果
                        using (Stream outputStream = context.Response.OutputStream)
                        {
                            string response = "{"LoginState":{"1"}}";
                            byte[] bf = Encoding.UTF8.GetBytes(response);
                            outputStream.Write(bf, 0, bf.Length);
                        }
                    }
                }
                context.Response.OutputStream.Close();
                Console.WriteLine("关闭会话。" + DateTime.Now.ToString());
            }
            catch(Exception ex)
            { 
                Console.WriteLine("验证用户信息失败:" + ex.Message);
            }
        }
    }

客户端代码

 /// <summary>
    /// 该类用于连接服务器
    /// </summary>
    public class ConnectServer
    {
        private const string SERVER_URL = "http://127.0.0.1:2222/";
        private AutoResetEvent _done = new AutoResetEvent(false);
        public void RequestConnect(string user,string password)
        {
            //创建用户登录Json
            string loginJson = CreateJson(user,password);
            //定义头信息
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SERVER_URL);
            request.Method = "POST";
            //request.AllowWriteStreamBuffering = true;
            RequestState requestState = new RequestState
            {
                UserJson = loginJson,
                Request = request
            };
            //开始对用来写入数据的 Stream 对象的异步请求
            request.BeginGetRequestStream(new AsyncCallback(BeginRequest), requestState);
        }
        /// <summary>
        /// 创建登录Json
        /// </summary>
        /// <param name="user">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>string</returns>
        private string CreateJson(string user, string password)
        {
            return "{"UserInfo":{"user":"" + user + "","password":"" + password + ""}}";
        }
        /// <summary>
        /// 开始回调读取方法
        /// </summary>
        /// <param name="ar"></param>
        private void BeginRequest(IAsyncResult ar)
        {
            RequestState requestState = ar.AsyncState as RequestState;
            using (StreamWriter sw = new StreamWriter(requestState.Request.EndGetRequestStream(ar)))
            {
                sw.Write(requestState.UserJson);
                sw.Flush();
                sw.Close();
            }
            //开始对 Internet 资源的异步请求。
            requestState.Request.BeginGetResponse(new AsyncCallback(BeginResponse), requestState);
            //等待释放信号
            _done.WaitOne();
        }
        //开始对 Internet 资源的异步请求。
        private void BeginResponse(IAsyncResult ar)
        {
            try
            {
                //RequestState requestState = ar.AsyncState as RequestState;
                HttpWebRequest requestState = ar.AsyncState as HttpWebRequest;
                WebResponse response = requestState.EndGetResponse(ar);
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader streamReader = new StreamReader(responseStream);
                    string context = streamReader.ReadToEnd();
                }
                //关闭响应
                response.GetResponseStream().Close();
                //发送释放信号
                _done.Set();
            }
            catch
            {
                MessageBox.Show("登录失败。", "提示", MessageBoxButton.OK);
            }
        }
    }
解决方案

35

也就是 http://127.0.0.1:80/     –>      也就是 http://127.0.0.1:2222/
silverlight 首先会使用 get 方式来下载   http://127.0.0.1:2222/clientaccesspolicy.xml   文件。这个只要你进行 http 调试,你就不可能先多余地去跑到 silverlight 代码里边去找 bug 了。

5

这个post好像的确有问题..
上次给别人的代码 他也是POST不行 get可以.. 具体是怎么样解决 本人还真不清楚.
不过 本人是不知道的..原因是假如是本人 本人不会用http协议…
原因是你这跟http没关系…本人可能采用tcp/ip.

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# HttpListener建立Http服务器并使用Silverlight来发送POST请求的疑问
喜欢 (0)
[1034331897@qq.com]
分享 (0)