Пример #1
0
        /// <summary>
        /// 收到监听内容回调处理
        /// </summary>
        /// <param name="asyncResult">异步结束状态</param>
        private void GetContextAsynCallback(IAsyncResult asyncResult)
        {
            // 收到客户端请求时回调函数
            // 异步操作完成
            // 推送操作:解析数据,添加到数据
            // 获取操作:从数据库获取数据并发送到客户端
            if (asyncResult.IsCompleted)
            {
                // 使用异步线程处理回调信息
                Task.Factory.StartNew(new Action(delegate
                {
                    try
                    {
                        // 获取HttpListener监听请求内容
                        HttpListenerContext httpListenerContext = serverListener.EndGetContext(asyncResult);
                        httpListenerContext.Response.StatusCode = mStatusCode;
                        HttpListenerRequest request             = httpListenerContext.Request;

                        // 客户端请求类型判断
                        if (request.HttpMethod == "POST")
                        {
                            // 解析请求的json数据流,返回用户信息实体
                            Stream stream     = request.InputStream;
                            UserInfo userInfo = AnalysisService.AnalysisJsonStre(stream, mEncoding);

                            // 用户数据判断是否为空
                            if (userInfo != null)
                            {
                                UserInfoDAL.AddUserInfo(userInfo);//// 更新用户信息到数据库
                            }
                        }

                        #region 通过客户端请求更新

                        String responseString = String.Empty;
                        if (request.HttpMethod == "GET")
                        {
                            List <UserInfo> userInfoList = UserInfoDAL.QueryAllUserInfo();

                            // 收到连接请求回传
                            responseString = JsonConvert.SerializeObject(userInfoList);
                        }

                        // 将数据转换为byte[]
                        byte[] buffer = Encoding.UTF8.GetBytes(responseString);

                        HttpListenerResponse response = httpListenerContext.Response;
                        response.ContentLength64      = buffer.Length;

                        // 写入输出json数据流
                        using (Stream outputStream = response.OutputStream)
                        {
                            outputStream.Write(buffer, 0, buffer.Length);
                            outputStream.Close();
                        }

                        #endregion

                        #region 互相监听时更新数据

                        // 由于客户端地址只有一个开启多个客户端使用时异常
                        //GetResponseData();

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("处理回调信息时异常:" + ex);
                    }
                }));
            }

            // 再次开启异步接收
            serverListener.BeginGetContext(callBack, null);
        }