internal HttpListenerContext (HttpConnection cnc)
		{
			this.cnc   = cnc;
			err_status = 400;
			request    = new HttpListenerRequest (this);
			response   = new HttpListenerResponse (this);
		}
 internal HttpListenerContext(HttpConnection cnc, ILogger logger)
 {
     this.cnc = cnc;
     _logger = logger;
     request = new HttpListenerRequest(this);
     response = new HttpListenerResponse(this, _logger);
 }
Exemple #3
0
 static void ErrorResponse(HttpListenerResponse response, Int32 status, Exception e)
 {
     response.StatusCode  = 200;
     response.ContentType = "text/plain";
     var content = Encoding.Unicode.GetBytes(e.ToString() + "\n");
     response.AppendHeader("Content-Length", content.Length.ToString());
     response.OutputStream.Write(content, 0, content.Length);
 }
 public HttpListenerCommunicationContext(IHost host, HttpListenerContext nativeContext)
 {
     ServerErrors = new List<Error>();
     PipelineData = new PipelineData();
     _host = host;
     User = nativeContext.User;
     Request = new HttpListenerRequest(this, nativeContext.Request);
     Response = new HttpListenerResponse(this, nativeContext.Response);
 }
Exemple #5
0
    private static void HandleCharacter(Match match, HttpListenerResponse response)
    {
        // here we are running in a thread different from the main thread
        int pid = Convert.ToInt32(match.Groups[1].Value);

        string responseString = "";

        // event used to wait the answer from the main thread.
        AutoResetEvent autoEvent = new AutoResetEvent(false);

        // var to store the character we are looking for
        Character character = null;
        // this bool is to check character is valid ... explanation below
        bool found = false;

        // we queue an 'action' to be executed in the main thread
        MainGameObject.QueueOnMainThread(()=>{
            // here we are in the main thread (see Update() in MainGameObject.cs)
            // retrieve the character
            character = MainGameObject.Instance().CharacterByID(pid);
            // if the character is null set found to false
            // have to do this because cannot call "character==null" elsewhere than the main thread
            // do not know why (yet?)
            // so if found this "trick"
            found = (character!=null?true:false);
            // set the event to "unlock" the thread
            autoEvent.Set();
        });

        // wait for the end of the 'action' executed in the main thread
        autoEvent.WaitOne();

        // generate the HTTP answer

        if (found==false) {
            responseString = "<html><body>character: not found (" + pid + ")</body></html>";
        } else {
            responseString = "<html><body>";
            responseString += "<img src='data:image/jpg;base64," + character.imageB64 + "'></img></br>";
            responseString += "name: " +  character.name + "</br>";
            responseString += "life: " +  character.life + "</br>";
            responseString += "streght " +  character.streght + "</br>";
            responseString += "dexterity " +  character.dexterity + "</br>";
            responseString += "consitution " +  character.consitution + "</br>";
            responseString += "intelligence " +  character.intelligence + "</br>";
            responseString += "</body></html>";
        }

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer,0,buffer.Length);
        // You must close the output stream.
        output.Close();
    }
 static void WriteResponse(HttpListenerResponse response, HttpStatusCode statusCode)
 {
     response.StatusCode = (int)statusCode;
     string text = statusCode.ToString();
     using (StreamWriter streamWriter = new StreamWriter(response.OutputStream))
     {
         streamWriter.Write(text);
     }
     response.StatusDescription = text;
 }
Exemple #7
0
    static void ApiResponse(HttpListenerResponse response, HttpListenerRequest request)
    {
        response.StatusCode  = 200;
        response.ContentType = "application/json";

        ApiData r = new ApiData();
        r.Status = 200;
        r.Value  = "foo";

        var serializer = new DataContractJsonSerializer(typeof(ApiData));

        serializer.WriteObject(response.OutputStream, r);
    }
Exemple #8
0
    static bool DeliverGateRoute(HttpListenerResponse response, string startSystem, string endSystem)
    {
        var start = LookupSystem(startSystem);
          var end = LookupSystem(endSystem);
          if (end == null)
          return false;

          var routeParams = new GateRouteParameters();
          routeParams.RoutingOption = GateRouteOption.UseBridges;
          routeParams.ShipMass = 1f;

          var router = new GateRouter(routeParams);
          List<Vertex> path;
          router.GetShortestPath(start, end, out path);

          if (path.Count == 0)
          return false;

          response.ContentType = "text/plain";

          var b = new StringBuilder();
          b.Append("{\"route\": [\n");

          foreach (var jump in path)
          {
          b.Append("{");

          b.Append("\"name\":\"").Append(jump.SolarSystem.Name).Append("\",");
          b.Append("\"id\":\"").Append(jump.SolarSystem.ID).Append("\",");
          b.Append("\"type\":\"").Append(jump.JumpType).Append("\"");

          if (jump.JumpType == JumpType.Bridge)
          {
              b.Append(",\"pos\":\"").Append(jump.Bridge.Pos.Planet).Append("-").Append(jump.Bridge.Pos.Moon).Append("\"");
          }

          b.Append("}");

          if (jump != path[path.Count - 1])
              b.Append(",\n");
          }
          b.Append("] }");

          response.ContentType = "application/json";
          RespondWith(response, b.ToString());

          return true;
    }
Exemple #9
0
    static bool DeliverFile(HttpListenerResponse response, string filename = "index.html")
    {
        var validFiles = new Dictionary<string, string>
                        {
                            {"index.html", "text/html;charset=utf-8"},
                            {"style.css", "text/css;charset=utf-8"},
                            {"app.js", "text/javascript;charset=utf-8"}
                        };

          if (validFiles.ContainsKey(filename))
          {
          response.ContentType = validFiles[filename];
          RespondWith(response, File.ReadAllBytes(filename));
          return true;
          }
          return false;
    }
Exemple #10
0
    private static void HandleCharacters(Match match, HttpListenerResponse response)
    {
        string responseString = "<html><body><div align='center'>";

        foreach (Character c in MainGameObject.Instance().characters) {
            responseString += "<p><a href='/character/" + c.cid + "'><img src=\"data:image/jpg;base64," + c.imageB64 + "\"></img></br>" + c.name + "</br></a></p>";
        }

        responseString += "</div></body></html>";

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer,0,buffer.Length);
        // You must close the output stream.
        output.Close();
    }
Exemple #11
0
        /// <summary>
        /// 收到监听内容回调处理
        /// </summary>
        /// <param name="asyncResult">异步结束状态</param>
        private void GetContextAsynCallback(IAsyncResult asyncResult)
        {
            // 收到客户端请求时回调函数
            // 异步操作完成
            // 推送操作:解析数据,添加到数据
            // 获取操作:从数据库获取数据并发送到客户端
            if (!asyncResult.IsCompleted)
            {
                serverListener.BeginGetContext(callBack, null);
            }

            // 使用异步线程处理回调信息
            Task.Factory.StartNew(new Action(delegate
            {
                HttpListenerContext ctx = serverListener.EndGetContext(asyncResult);
                ctx.Response.StatusCode = mStatusCode;

                HttpListenerRequest request = ctx.Request;

                HttpListener httpListener = new HttpListener();
                //HttpContext httpContext = new HttpContext(ActionLink("TEXT", "ACTION", "CONTROLLER"));
                HttpListenerContext httpCont = httpListener.GetContext();
                //HttpRequest httpRequest = httpContext.Request;

                // 请求类型判断
                if (request.HttpMethod == "POST")
                {
                    // 解析数据
                    Stream stream     = request.InputStream;
                    UserInfo userInfo = new UserInfo(); //AnalysisService.AnalysisJsonStre(stream, mEncoding);

                    // 数据判断
                    if (userInfo != null)
                    {
                        UserInfoDAL.AddUserInfo(userInfo);//// 更新数据库
                    }
                }

                #region 通过客户端请求更新

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

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

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

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

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

                #endregion

                #region 互相监听时更新数据

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

                #endregion
            }));
        }
        public async void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;

            if (!listener.IsListening)
            {
                string err_msg = "!listener.IsListening";
                Log.Debug(TAG, err_msg);
                logsDB.AddLogRow(LogStatusesEnum.Error, err_msg, TAG);
                return;
            }
            // Call EndGetContext to complete the asynchronous operation.
            HttpListenerContext context = listener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            string remote_ip_address    = request.RemoteEndPoint.Address.ToString();

            string s_request = $"ListenerCallback() - request: {request.Url} from > {remote_ip_address}";

            Log.Debug(TAG, s_request);
            logsDB.AddLogRow(LogStatusesEnum.Info, s_request, TAG);

            // Obtain a response object.
            HttpListenerResponse response = context.Response;

            Android.Net.Uri uri = Android.Net.Uri.Parse(request.Url.ToString());

            string pt    = uri.GetQueryParameter("pt");
            string dir   = uri.GetQueryParameter("dir");
            string mdid  = uri.GetQueryParameter("mdid");
            string v     = uri.GetQueryParameter("v");
            string value = uri.GetQueryParameter("value");
            string st    = uri.GetQueryParameter("st");
            string m     = uri.GetQueryParameter("m");
            string click = uri.GetQueryParameter("click");
            string cnt   = uri.GetQueryParameter("cnt");

            HardwareModel hardware;
            string        hw_name = string.Empty;

            lock (DatabaseContext.DbLocker)
            {
                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                {
                    hardware = db.Hardwares.FirstOrDefault(x => x.Address == remote_ip_address);
                }
            }

            hw_name = hardware?.Name ?? string.Empty;
            if (string.IsNullOrEmpty(hw_name))
            {
                hw_name = remote_ip_address;
            }
            else
            {
                hw_name += $" ({remote_ip_address})";
            }

            string bot_message = $"Сообщение от устройства \"{hw_name}\": {Environment.NewLine}";

            if (!string.IsNullOrWhiteSpace(pt))
            {
                if (Regex.IsMatch(pt, @"^\d+$"))
                {
                    PortModel portHardware = null;
                    int       pt_num_int   = -1;
                    pt_num_int = int.Parse(pt);
                    if (pt_num_int > -1 && hardware != null)
                    {
                        lock (DatabaseContext.DbLocker)
                        {
                            using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                            {
                                portHardware = db.Ports.FirstOrDefault(x => x.HardwareId == hardware.Id && x.PortNumb == pt_num_int);
                            }
                        }
                        if (portHardware != null)
                        {
                            Log.Debug(TAG, "Поиск триггера");

                            List <ScriptModel> scripts_triggers = null;
                            lock (DatabaseContext.DbLocker)
                            {
                                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                                {
                                    scripts_triggers = db.Scripts.Where(x => x.TriggerPortId == portHardware.Id).Include(x => x.Commands).ToList();
                                }
                            }
                            if (scripts_triggers != null && scripts_triggers.Count > 0)
                            {
                                Log.Debug(TAG, $"Нaйдено триггеров: {scripts_triggers.Count}");
                                foreach (ScriptModel trigger_script in scripts_triggers)
                                {
                                    string url_request_port_state = $"http://{hardware.Address}/{hardware.Password}/?pt={pt}&cmd=get";
                                    Log.Debug(TAG, $"Зпрос состояния порта: {url_request_port_state}");

                                    HttpWebRequest request_port_state = new HttpWebRequest(new Uri(url_request_port_state))
                                    {
                                        Timeout = 5000
                                    };
                                    try
                                    {
                                        using (HttpWebResponse response_port_state = (HttpWebResponse)request_port_state.GetResponse())
                                        {
                                            if (response_port_state.StatusCode == HttpStatusCode.OK)
                                            {
                                                string responseFromServer = string.Empty;

                                                using (Stream dataStream = response_port_state.GetResponseStream())
                                                    using (StreamReader reader = new StreamReader(dataStream))
                                                    {
                                                        responseFromServer = reader.ReadToEnd();
                                                    }
                                                if (string.IsNullOrEmpty(responseFromServer))
                                                {
                                                    //"Пустой ответ устройства.";
                                                    continue;
                                                }
                                                else if (responseFromServer.ToLower() == "unauthorized")
                                                {
                                                    //"Пароль, указаный в настройкх устройства не подошёл.";
                                                    continue;
                                                }
                                                else
                                                {
                                                    Log.Debug(TAG, $"Cостояние порта: {responseFromServer}");
                                                    if ((trigger_script.TriggerPortState == true && !responseFromServer.ToLower().StartsWith("on/")) || (trigger_script.TriggerPortState == false && responseFromServer.ToLower().StartsWith("off/")))
                                                    {
                                                        continue;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //$"Ошибка выполнения запроса. StatusCode:\"{response.StatusCode}\"; StatusDescription:\"{response.StatusDescription}\"";
                                                continue;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //$"Сбой обработки команды:{ex.Message}";
                                        continue;
                                    }


                                    TaskModel task;
                                    lock (DatabaseContext.DbLocker)
                                    {
                                        using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                                        {
                                            task = new TaskModel()
                                            {
                                                Name = "http trigger",
                                                TaskInitiatorType = TaskInitiatorsTypes.Trigger,
                                                TaskInitiatorId   = hardware.Id,
                                                ScriptId          = trigger_script.Id
                                            };
                                            db.Tasks.Add(task);
                                            db.SaveChanges();
                                        }
                                    }

                                    BackgroundWorker bw = new BackgroundWorker();
                                    bw.DoWork             += new DoWorkEventHandler(aForegroundService.RunScriptAction);
                                    bw.ProgressChanged    += (object sender, ProgressChangedEventArgs e) => { };
                                    bw.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => { };
                                    bw.RunWorkerAsync(task);
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(pt) && string.IsNullOrWhiteSpace(portHardware?.Name))
                    {
                        pt = $"Порт: P{pt}; ";
                    }
                    else
                    {
                        pt = $"Порт: \"{portHardware.Name}\" (P{pt}); ";
                    }
                }
                else
                {
                    pt = $"Порт: {pt}; ";
                }
                bot_message += $"{pt}";
            }

            if (!string.IsNullOrWhiteSpace(m))
            {
                m            = (m == "1" ? "Освобождние после длительного удержания" : $"Длительное удержание") + "; ";
                bot_message += $"{m}";
            }

            if (!string.IsNullOrWhiteSpace(click))
            {
                click        = (click == "1" ? "обычный клик" : "двойной клик") + "; ";
                bot_message += $"{click}";
            }

            if (!string.IsNullOrWhiteSpace(dir))
            {
                if (dir == "0")//падение значения
                {
                    dir = "Значение опустилось ниже порога; ";
                }
                else if (dir == "1")//повышение знчения
                {
                    dir = "Значение превышает пороговое; ";
                }
                else
                {
                    dir = $"ошибка определения вектора 'dir':{dir}; ";
                }
                bot_message += $"{dir}";
            }

            if (!string.IsNullOrWhiteSpace(mdid))
            {
                mdid         = $"mdid=\"{mdid}\"; ";
                bot_message += $"{mdid}";
            }

            if (!string.IsNullOrWhiteSpace(st))
            {
                st           = $"st=\"{st}\"; ";
                bot_message += $"{st}";
            }

            if (!string.IsNullOrWhiteSpace(v))
            {
                v            = $"v=\"{v}\"; ";
                bot_message += $"{v}";
            }

            if (!string.IsNullOrWhiteSpace(value))
            {
                value        = $"value=\"{value}\"; ";
                bot_message += $"{value}";
            }

            string token = Preferences.Get(Constants.TELEGRAM_TOKEN, string.Empty);

            if (!string.IsNullOrWhiteSpace(token))
            {
                TelegramClientCore telegramClient = new TelegramClientCore(token);
                if (telegramClient?.Me != null)
                {
                    List <UserModel> users;
                    lock (DatabaseContext.DbLocker)
                    {
                        using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                        {
                            users = db.Users.Where(x => x.AlarmSubscriber).ToList();
                        }
                    }

                    List <TelegramUserModel> t_users;
                    foreach (UserModel user in users)
                    {
                        lock (DatabaseContext.DbLocker)
                        {
                            using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                            {
                                t_users = db.TelegramUsers.Where(xx => xx.LinkedUserId == user.Id).ToList();
                            }
                        }
                        foreach (TelegramUserModel telegramUser in t_users)
                        {
                            await telegramClient.sendMessage(telegramUser.TelegramId.ToString(), bot_message.Trim());
                        }
                    }
                }
            }

            string log_msg = $"incoming http request (from > {remote_ip_address}): {request.Url.Query}";
            //log_msg = "telegramClient?.Me == null";
            //Log.Info(TAG, log_msg);
            //using (LogsContext log = new LogsContext())
            //{
            //    log.AddLogRow(LogStatusesEnum.Info, log_msg, TAG);
            //}

            // Construct a response.
            string responseString = "Hello world!";

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            await output.WriteAsync(buffer, 0, buffer.Length);

            // You must close the output stream.
            output.Close();
            result = httpServer.BeginGetContext(new AsyncCallback(ListenerCallback), httpServer);
        }
Exemple #13
0
 private static void sendFile(HttpListenerRequest request,HttpListenerResponse response)
 {
     String file = VolumeInfo.GetVolumes()[0].RootDirectory + formatUrl(request.RawUrl);
     FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
     byte[] page = new byte[1024];
     while (fs.Read(page, 0, 1024) > 0)
     {
         response.OutputStream.Write(page, 0, page.Length);
         Array.Clear(page, 0, 1024);
         Debug.GC(true);
     }
     fs.Close();
 }
 public static T ResolveService <T>(HttpListenerRequest httpReq, HttpListenerResponse httpRes)
     where T : class, IRequiresRequestContext
 {
     return(ResolveService <T>(httpReq.ToRequest(), httpRes.ToResponse()));
 }
Exemple #15
0
        public static void OnIncomingRequest(HttpListenerContext context)
        {
            if (context == null)
            {
                return;
            }
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            if (IsDebugginMode)
            {
                String address = request.RemoteEndPoint.Address.ToString();
                String method  = request.HttpMethod;
                String host    = request.Url.Host;
                String path    = request.Url.AbsolutePath;
                Log.Write(String.Format("address: {0}, method: {1}, host: {2}, path: {3}", address, method, host, path));
            }
            if (Http.RequestIsAcceptable(request))
            {
                // разбор запроса
                Encoding enc  = Encoding.UTF8;
                String   body = null;
                using (StreamReader sr = new StreamReader(request.InputStream, enc))
                {
                    body = sr.ReadToEnd();
                }
                if (!String.IsNullOrWhiteSpace(body))
                {
                    if (IsDebugginMode)
                    {
                        Log.Write("Request.InputStream: " + body);
                    }
                    RequestPackage rqp = null;
                    switch (body[0])
                    {
                    case '<':
                        rqp = RequestPackage.ParseXml(body);
                        break;

                    case '{':
                        rqp = RequestPackage.ParseJson(body);
                        break;

                    default:
                        break;
                    }
                    if (rqp != null)
                    {
                        // исполнение запроса
                        ResponsePackage rsp = SqlServer.Exec(rqp);
                        // запись ответа
                        Byte[] buff = (rsp == null) ? new Byte[0] : rsp.ToXml(enc);
                        if (IsDebugginMode)
                        {
                            Log.Write("Response.OutputStream: " + enc.GetString(buff));
                        }
                        response.OutputStream.Write(buff, 0, buff.Length);
                    }
                    else
                    {
                        Log.Write("Непонятен формат запроса: " + body);
                    }
                }
                else
                {
                    Log.Write("Запрос пуст.");
                }
            }
            else
            {
                Log.Write("Запрос не прошел проверку.");
            }
        }
Exemple #16
0
 /// <summary>
 /// 返回Html数据
 /// </summary>
 /// <param name="response"></param>
 /// <param name="html"></param>
 protected void Html(HttpListenerResponse response, string html)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(html);
     CreateResponse(response, buffer, "text/html");
 }
        // Keep on handling requests
        public static async Task HandleIncomingConnections()
        {
            while (true)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                int    status            = 200;
                string statusDescription = "OK";
                string json = "";

                Error[] errors = new Error[1];

                if (req.Url.AbsolutePath == "/" + type)
                {
                    //OK
                    if (req.HttpMethod == "GET")
                    {   //Return sessionid
                        try
                        {
                            //Create new payment session
                            Session session = new Session(Double.Parse(req.QueryString["amount"]),
                                                          req.QueryString["purpose"]);
                            json = JsonConvert.SerializeObject(new Data(type,
                                                                        session.sessionId.ToString()));
                        }
                        catch (Exception e)
                        {
                            //Error: amount or purpose is not exists
                            errors[0]         = new Error(400, "Amount or purpose is missing!", 6);
                            json              = JsonConvert.SerializeObject(errors);
                            status            = 400;
                            statusDescription = "Bad Request";
                            Console.WriteLine(e);
                        }
                    }
                    else if (req.HttpMethod == "POST")
                    {   //Make payment
                        try
                        {
                            //Read request body
                            dynamic request = JsonConvert.DeserializeObject(
                                ReadInputStream(req.InputStream));

                            if (request.type == type)
                            {
                                Session session = Session.Find(Guid.Parse((string)request.id));
                                if (session != null)
                                {
                                    Card card = new Card((string)request.attributes.number, (int)request.attributes.CVVCVC,
                                                         (int)request.attributes.year, (int)request.attributes.mounth,
                                                         (string)request.attributes.URL);

                                    //Сheck the data is full
                                    if (card.number.Length >= 4 && card.CVVCVC >= 100 && card.CVVCVC <= 999 &&
                                        card.mounth >= 1 && card.year >= 0 && card.URL != "")
                                    {
                                        //Check the card number in Luna algorithm
                                        if (SimpleLuna(card.number))
                                        {
                                            //Payment successful
                                            json = JsonConvert.SerializeObject(new Data(type,
                                                                                        session.sessionId.ToString()));

                                            //Send http-notice
                                            HttpNotice(card.URL, session.sessionId, session.purpose,
                                                       card.number, session.amount);
                                        }
                                        else
                                        {
                                            //Error: the card number is not correct
                                            errors[0]         = new Error(400, "The card number is not correct!", 1);
                                            json              = JsonConvert.SerializeObject(errors);
                                            status            = 400;
                                            statusDescription = "Bad Request";
                                        }
                                    }
                                    else
                                    {
                                        //Error: the card data is not correct
                                        errors[0]         = new Error(400, "The card data is not correct!", 2);
                                        json              = JsonConvert.SerializeObject(errors);
                                        status            = 400;
                                        statusDescription = "Bad Request";
                                    }

                                    //Delete used session
                                    Session.list.Remove(session);
                                }
                                else
                                {
                                    //Error: dead session
                                    errors[0]         = new Error(400, "Dead session!", 3);
                                    json              = JsonConvert.SerializeObject(errors);
                                    status            = 400;
                                    statusDescription = "Bad Request";
                                }
                            }
                            else
                            {
                                //Error: unknown request type
                                errors[0]         = new Error(400, "Unknown request type!", 4);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                        }
                        catch (Exception e)
                        {
                            if (e.GetType().Name == "UriFormatException")
                            {
                                errors[0]         = new Error(400, "Invalid URL!", 4);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                            else if (e.GetType().Name == "FormatException")
                            {
                                errors[0]         = new Error(400, "Bad Request", 7);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                            else
                            {
                                //Error: 500 - Internal Server Error
                                status            = 500;
                                statusDescription = "Internal Server Error";
                                Console.WriteLine(e);
                            }
                        }
                    }
                    else
                    {
                        //Error: unknown method
                        errors[0]         = new Error(400, "Unknown method!", 5);
                        json              = JsonConvert.SerializeObject(errors);
                        status            = 400;
                        statusDescription = "Bad Request";
                    }
                }
                else
                {
                    //Error: resource not found
                    status            = 404;
                    statusDescription = "Not Found";
                }

                byte[] data = Encoding.UTF8.GetBytes(json);
                resp.StatusCode        = status;
                resp.StatusDescription = statusDescription;
                resp.ContentType       = "application/vnd.api+json";
                resp.ContentEncoding   = Encoding.UTF8;
                resp.ContentLength64   = data.LongLength;

                // Write out to the response stream (asynchronously), then close it
                await resp.OutputStream.WriteAsync(data, 0, data.Length);

                resp.Close();
            }
        }
Exemple #18
0
 /// <summary>
 /// 返回文本数据
 /// </summary>
 /// <param name="response"></param>
 /// <param name="text"></param>
 protected void Text(HttpListenerResponse response, string text)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(text);
     CreateResponse(response, buffer, "text/plain");
 }
Exemple #19
0
 /// <summary>
 /// 返回Json数据
 /// </summary>
 /// <param name="response"></param>
 /// <param name="json"></param>
 protected void Json(HttpListenerResponse response, string json)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(json);
     CreateResponse(response, buffer, "application/json");
 }
Exemple #20
0
 /// <summary>
 /// 请求处理函数
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response"></param>
 public abstract void Handler(HttpListenerRequest request, HttpListenerResponse response);
Exemple #21
0
        private static async Task GetSpotifyCredentials()
        {
            string code = null;

            Console.WriteLine("Begin Spotify code aquisition");

            // Temporarily hosts a web server to get redirect information
            var listener = new HttpListener();

            listener.Prefixes.Add("http://localhost:8888/callback/");
            listener.Start();
            IAsyncResult result = listener.BeginGetContext(new AsyncCallback((callback) =>
            {
                HttpListener listen         = (HttpListener)callback.AsyncState;
                HttpListenerContext context = listen.EndGetContext(callback);
                HttpListenerRequest request = context.Request;
                code = request.QueryString["code"];

                HttpListenerResponse response = context.Response;
                string responseString         = "<HTML><BODY><H1>Authentication successful. You may now close this page.</H1></BODY></HTML>";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output  = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // Close the output stream
                output.Close();
            }), listener);

            // Generates a secure random verifier of length 100 and its challenge
            var(verifier, challenge) = PKCEUtil.GenerateCodes();

            var loginRequest = new LoginRequest(
                new Uri("http://localhost:8888/callback"),
                clientId,
                LoginRequest.ResponseType.Code
                )
            {
                CodeChallengeMethod = "S256",
                CodeChallenge       = challenge,
                Scope = new[] { Scopes.UserReadCurrentlyPlaying, Scopes.UserReadPlaybackState }
            };
            var uri = loginRequest.ToUri();

            Console.WriteLine("Attempting to start browser...");
            Process.Start(uri.ToString());

            // Wait 5 minutes or until code value is fulfilled
            for (int i = 0; i < 300; i++)
            {
                if (code != null)
                {
                    break;
                }
                Console.WriteLine($"Waiting for user to connect account... ({i}/300 sec)");
                Thread.Sleep(1000);
            }

            if (code == null)
            {
                Console.WriteLine("Failed to fetch code! Press any key to continue...");
                Console.ReadKey();
                Environment.Exit(1);
            }
            Console.WriteLine("Code aquisition successful");
            listener.Stop();

            // Log in to Spotify
            // Note that we use the verifier calculated above!
            var initialResponse = await new OAuthClient().RequestToken(
                new PKCETokenRequest(clientId, code, new Uri("http://localhost:8888/callback"), verifier)
                );

            WriteOAuthCreds(initialResponse);
            Console.WriteLine("Credential file written");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemple #22
0
        // This example requires the System and System.Net namespaces.
        public static void SimpleListenerExample(string[] prefixes)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            // URI prefixes are required,
            // for example "http://contoso.com:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }
            listener.Start();
            Console.WriteLine("Listening...");
            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                string responseString;
                // Construct a response.
                try
                {
                    if (request.RawUrl.Contains(".gif"))
                    {
                        response.AddHeader("ContentType", "image/gif");
                    }
                    responseString = File.ReadAllText(@"D:\skola\molöntjänster\webserver2-grupp1\Content\" + request.RawUrl);
                }
                catch (Exception)
                {
                    continue;
                }
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);

                // You must close the output stream.
                output.Close();
                Console.WriteLine($"raw url{request.RawUrl}");
            }
            listener.Stop();
        }
Exemple #23
0
        private async void OnContext(IAsyncResult res)
        {
            HttpListenerContext ctx = _listener.EndGetContext(res);

            _listener.BeginGetContext(OnContext, null);

            await _requestLock.WaitAsync();

            try
            {
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                if (req.HttpMethod == "POST" && req.Url.AbsolutePath == "/submit")
                {
                    using (var reader = new StreamReader(req.InputStream, req.ContentEncoding))
                    {
                        string        postStr = reader.ReadToEnd();
                        List <string> twitchChannels = new List <string>(), mixerChannels = new List <string>();

                        Dictionary <string, string> postDict = new Dictionary <string, string>();
                        foreach (var postData in postStr.Split('&'))
                        {
                            try
                            {
                                var split = postData.Split('=');
                                postDict[split[0]] = split[1];

                                switch (split[0])
                                {
                                case "twitch_oauthtoken":
                                    var twitchOauthToken = HttpUtility.UrlDecode(split[1]);
                                    _authManager.Credentials.Twitch_OAuthToken = twitchOauthToken.StartsWith("oauth:") ? twitchOauthToken : !string.IsNullOrEmpty(twitchOauthToken) ? $"oauth:{twitchOauthToken}" : "";
                                    break;

                                case "twitch_channel":
                                    string twitchChannel = split[1].ToLower();
                                    if (!string.IsNullOrWhiteSpace(twitchChannel) && !_authManager.Credentials.Twitch_Channels.Contains(twitchChannel))
                                    {
                                        _authManager.Credentials.Twitch_Channels.Add(twitchChannel);
                                    }
                                    _logger.LogInformation($"TwitchChannel: {twitchChannel}");
                                    twitchChannels.Add(twitchChannel);
                                    break;

                                case "mixer_channel":
                                    string mixerChannel = split[1].ToLower();
                                    if (!string.IsNullOrWhiteSpace(mixerChannel) && !_authManager.Credentials.Mixer_Channels.Contains(mixerChannel))
                                    {
                                        _authManager.Credentials.Mixer_Channels.Add(mixerChannel);
                                    }
                                    _logger.LogInformation($"MixerChannel: {mixerChannel}");
                                    mixerChannels.Add(mixerChannel);
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "An exception occurred in OnLoginDataUpdated callback");
                            }
                        }
                        foreach (var channel in _authManager.Credentials.Twitch_Channels.ToArray())
                        {
                            // Remove any channels that weren't present in the post data
                            if (!twitchChannels.Contains(channel))
                            {
                                _authManager.Credentials.Twitch_Channels.Remove(channel);
                            }
                        }
                        foreach (var channel in _authManager.Credentials.Mixer_Channels.ToArray())
                        {
                            // Remove any channels that weren't present in the post data
                            if (!mixerChannels.Contains(channel))
                            {
                                _authManager.Credentials.Mixer_Channels.Remove(channel);
                            }
                        }
                        _authManager.Save();
                        _settings.SetFromDictionary(postDict);
                        _settings.Save();
                    }
                    resp.Redirect(req.UrlReferrer.OriginalString);
                    resp.Close();
                    return;
                }
                StringBuilder pageBuilder             = new StringBuilder(pageData);
                StringBuilder twitchChannelHtmlString = new StringBuilder();
                for (int i = 0; i < _authManager.Credentials.Twitch_Channels.Count; i++)
                {
                    var channel = _authManager.Credentials.Twitch_Channels[i];
                    twitchChannelHtmlString.Append($"<span id=\"twitch_channel_{i}\" class=\"chip \">{channel}<input type=\"text\" class=\"form-input\" name=\"twitch_channel\" style=\"display: none; \" value=\"{channel}\" /><button type=\"button\" onclick=\"removeTwitchChannel('twitch_channel_{i}')\" class=\"btn btn-clear\" aria-label=\"Close\" role=\"button\"></button></span>");
                }
                StringBuilder mixerChannelHtmlString = new StringBuilder();
                for (int i = 0; i < _authManager.Credentials.Mixer_Channels.Count; i++)
                {
                    var channel = _authManager.Credentials.Mixer_Channels[i];
                    mixerChannelHtmlString.Append($"<span id=\"mixer_channel_{i}\" class=\"chip \">{channel}<input type=\"text\" class=\"form-input\" name=\"mixer_channel\" style=\"display: none; \" value=\"{channel}\" /><button type=\"button\" onclick=\"removeMixerChannel('mixer_channel_{i}')\" class=\"btn btn-clear\" aria-label=\"Close\" role=\"button\"></button></span>");
                }
                StringBuilder mixerLinkHtmlString = new StringBuilder();
                if (!string.IsNullOrEmpty(_authManager.Credentials.Mixer_RefreshToken))
                {
                    mixerLinkHtmlString.Append("<button class=\"btn btn-error\" onclick=\"window.location.href='mixer'\" type=\"button\">Click to unlink your Mixer account</button></br></br>");
                }
                else
                {
                    mixerLinkHtmlString.Append("<button class=\"btn btn-success\" onclick=\"window.location.href='mixer'\" type=\"button\">Click to link your Mixer account</button></br></br>");
                }
                var sectionHTML = _settings.GetSettingsAsHTML();
                pageBuilder.Replace("{WebAppSettingsHTML}", sectionHTML["WebApp"]);
                pageBuilder.Replace("{GlobalSettingsHTML}", sectionHTML["Global"]);
                pageBuilder.Replace("{TwitchSettingsHTML}", sectionHTML["Twitch"]);
                pageBuilder.Replace("{TwitchChannelHtml}", twitchChannelHtmlString.ToString());
                pageBuilder.Replace("{TwitchOAuthToken}", _authManager.Credentials.Twitch_OAuthToken);
                pageBuilder.Replace("{MixerSettingsHTML}", sectionHTML["Mixer"]);
                pageBuilder.Replace("{MixerChannelHtml}", mixerChannelHtmlString.ToString());
                pageBuilder.Replace("{MixerLinkHtml}", mixerLinkHtmlString.ToString());
                byte[] data = Encoding.UTF8.GetBytes(pageBuilder.ToString());
                resp.ContentType     = "text/html";
                resp.ContentEncoding = Encoding.UTF8;
                resp.ContentLength64 = data.LongLength;
                await resp.OutputStream.WriteAsync(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Exception occurred during webapp request.");
            }
            finally
            {
                _requestLock.Release();
            }
        }
Exemple #24
0
 private static void AddNoCacheHeaders(HttpListenerResponse response)
 {
     response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
     response.Headers.Add("Pragma", "no-cache");
     response.Headers.Add("Expires", "0");
 }
Exemple #25
0
        /// <summary>
        /// Loguje użytkownika przez konto Google (OAuth 2)
        /// </summary>
        private async Task AuthenticateWithGoogle()
        {
            // Generates state and PKCE values.
            string       state                 = RandomDataBase64url(32);
            string       code_verifier         = RandomDataBase64url(32);
            string       code_challenge        = Base64urlencodeNoPadding(Sha256(code_verifier));
            const string code_challenge_method = "S256";

            // Creates a redirect URI using an available port on the loopback address.
            string redirectURI = "http://localhost:8080/";

            // Creates an HttpListener to listen for requests on that redirect URI.
            using (HttpListener http = new HttpListener())
            {
                http.Prefixes.Add(redirectURI);
                http.Start();

                // Creates the OAuth 2.0 authorization request.
                string authorizationRequest = string.Format(CultureInfo.InvariantCulture, "{0}?response_type=code&scope=profile%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}&access_type=offline&approval_prompt=force",
                                                            authorizationEndpoint,
                                                            System.Uri.EscapeDataString(redirectURI),
                                                            clientID,
                                                            state,
                                                            code_challenge,
                                                            code_challenge_method);

                // Opens request in the browser.
                Process.Start(new ProcessStartInfo(authorizationRequest)
                {
                    UseShellExecute = true
                });

                // Waits for the OAuth authorization response.
                HttpListenerContext context = await http.GetContextAsync().ConfigureAwait(false);

                // Sends an HTTP response to the browser.
                HttpListenerResponse response = context.Response;
                string responseString         = string.Format(CultureInfo.InvariantCulture, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please return to the app.</body></html>");
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream responseOutput = response.OutputStream;
                Task   responseTask   = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
                {
                    responseOutput.Close();
                    http.Stop();
                });

                // Checks for errors.
                if (context.Request.QueryString.Get("error") != null)
                {
                    return;
                }
                if (context.Request.QueryString.Get("code") == null ||
                    context.Request.QueryString.Get("state") == null)
                {
                    return;
                }

                // extracts the code
                string code           = context.Request.QueryString.Get("code");
                string incoming_state = context.Request.QueryString.Get("state");

                // Compares the receieved state to the expected value, to ensure that
                // this app made the request which resulted in authorization.
                if (incoming_state != state)
                {
                    return;
                }

                // Starts the code exchange at the Token Endpoint.
                await PerformCodeExchange(code, code_verifier, redirectURI).ConfigureAwait(false);

                return;
            }
        }
Exemple #26
0
 private static void AddCORSHeaders(HttpListenerResponse response)
 {
     response.Headers.Add("Access-Control-Allow-Origin", "*");
     response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
 }
Exemple #27
0
        public static Tuple <int, byte[]> SendResponse(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (request.Url.AbsolutePath == "/")
            {
                response.ContentType = "text/html";

                var asmPath   = Assembly.GetExecutingAssembly().Location;
                var indexPath = Path.Combine(new FileInfo(asmPath).DirectoryName, "index.htm");
                using (var reader = new StreamReader(indexPath))
                {
                    return(new Tuple <int, byte[]>(200, Encoding.UTF8.GetBytes(reader.ReadToEnd().Replace("__PROTOCOL__", isServerIpv4 ? "ipv4" : "ipv6"))));
                }
            }

            if (request.Url.AbsolutePath == "/basic")
            {
                response.ContentType = "text/html";

                var asmPath   = Assembly.GetExecutingAssembly().Location;
                var indexPath = Path.Combine(new FileInfo(asmPath).DirectoryName, "basic.htm");
                using (var reader = new StreamReader(indexPath))
                {
                    return(new Tuple <int, byte[]>(200, Encoding.UTF8.GetBytes(reader.ReadToEnd().Replace("__PROTOCOL__", isServerIpv4 ? "ipv4" : "ipv6"))));
                }
            }

            if (request.Url.AbsolutePath == "/token")
            {
                response.ContentType = "text/plain";

                var buffer = new byte[sizeof(UInt64)];
                random.NextBytes(buffer);
                var clientId = BitConverter.ToUInt64(buffer, 0);

                Console.WriteLine($"Generating connect token for {serverAddress}:{serverPort}");
                var tokenFactory = new TokenFactory(
                    0x1122334455667788L,
                    _privateKey);
                var token = tokenFactory.GenerateConnectToken(
                    new[] { new IPEndPoint(IPAddress.Parse(serverAddress), int.Parse(serverPort)) },
                    60,
                    60,
                    0,
                    clientId,
                    new byte[0]);
                return(new Tuple <int, byte[]>(200, Encoding.UTF8.GetBytes(Convert.ToBase64String(token))));
            }

            if (request.Url.AbsolutePath == "/netcode-support.xpi")
            {
                response.ContentType = "application/x-xpinstall";

                var asmPath = Assembly.GetExecutingAssembly().Location;
                var xpiPath = Path.Combine(new FileInfo(asmPath).DirectoryName, "netcodeio_support_self_dist-0.1.5-fx.xpi");
                using (var reader = new FileStream(xpiPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var b = new byte[reader.Length];
                    reader.Read(b, 0, b.Length);
                    return(new Tuple <int, byte[]>(200, b));
                }
            }

            return(new Tuple <int, byte[]>(404, Encoding.UTF8.GetBytes("404 not found")));
        }
 static void RecordRequest(HttpStatusCode statusCode, HttpListenerRequest request, IDictionary <string, string> requestHeaders, HttpListenerResponse response, IDictionary <string, string> responseHeaders)
 {
     foreach (string name in request.Headers)
     {
         requestHeaders.Add(name, request.Headers[name]);
     }
     response.StatusCode  = (int)statusCode;
     response.ContentType = "application/json";
 }
Exemple #29
0
        //处理客户端请求
        private void HandleRequest(object ctx)
        {
            HttpListenerContext  context  = ctx as HttpListenerContext;
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            try
            {
                string rawUrl          = Uri.UnescapeDataString(request.RawUrl);
                int    paramStartIndex = rawUrl.IndexOf('?');
                if (paramStartIndex > 0)
                {
                    rawUrl = rawUrl.Substring(0, paramStartIndex);
                }
                else if (paramStartIndex == 0)
                {
                    rawUrl = "";
                }

                #region 文件请求

                {
                    string filePath = WebHomeDir + rawUrl;
                    //替换
                    // var platforms = BDApplication.GetSupportPlatform();
                    // foreach (var platform in platforms)
                    // {
                    //     var platformStr = BDApplication.GetPlatformPath(platform);
                    //     filePath = filePath.Replace(platformStr, platformStr + PublishPipelineTools.UPLOAD_FOLDER_SUFFIX);
                    // }

                    if (!File.Exists(filePath))
                    {
                        response.ContentLength64 = 0;
                        response.StatusCode      = 404;
                        response.Abort();
                    }
                    else
                    {
                        response.StatusCode = 200;
                        string exeName = Path.GetExtension(filePath);
                        response.ContentType = GetContentType(exeName);
                        FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                        int        byteLength = (int)fileStream.Length;
                        byte[]     fileBytes  = new byte[byteLength];
                        fileStream.Read(fileBytes, 0, byteLength);
                        fileStream.Close();
                        fileStream.Dispose();
                        response.ContentLength64 = byteLength;
                        response.OutputStream.Write(fileBytes, 0, byteLength);
                        response.OutputStream.Close();
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                response.StatusCode  = 200;
                response.ContentType = "text/plain";
                using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
                {
                    writer.WriteLine("接收完成!");
                }
            }

            try
            {
                response.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
Exemple #30
0
 virtual public void Handle(ref HttpListenerResponse response)
 {
 }
Exemple #31
0
        private void SendJson(HttpListenerResponse response, HttpListenerRequest request = null)
        {
            JObject json = new JObject();

            int nodeIndex = 0;

            json["id"]       = nodeIndex++;
            json["Text"]     = "Sensor";
            json["Min"]      = "Min";
            json["Value"]    = "Value";
            json["Max"]      = "Max";
            json["ImageURL"] = string.Empty;

            JArray children = new JArray {
                GenerateJsonForNode(_root, ref nodeIndex)
            };

            json["Children"] = children;
#if DEBUG
            string responseContent = json.ToString(Newtonsoft.Json.Formatting.Indented);
#else
            string responseContent = json.ToString(Newtonsoft.Json.Formatting.None);
#endif
            byte[] buffer = Encoding.UTF8.GetBytes(responseContent);

            bool acceptGzip;
            try
            {
                acceptGzip = (request != null) && (request.Headers["Accept-Encoding"].ToLower().IndexOf("gzip", StringComparison.OrdinalIgnoreCase) >= 0);
            }
            catch
            {
                acceptGzip = false;
            }

            if (acceptGzip)
            {
                response.AddHeader("Content-Encoding", "gzip");
            }

            response.AddHeader("Cache-Control", "no-cache");
            response.AddHeader("Access-Control-Allow-Origin", "*");
            response.ContentType = "application/json";
            try
            {
                if (acceptGzip)
                {
                    using (var ms = new MemoryStream())
                    {
                        using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
                            zip.Write(buffer, 0, buffer.Length);

                        buffer = ms.ToArray();
                    }
                }

                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
            catch (HttpListenerException)
            { }

            response.Close();
        }
Exemple #32
0
 static void RespondWith(HttpListenerResponse resp, string text)
 {
     var bytes = Encoding.UTF8.GetBytes(text);
     RespondWith(resp, bytes);
 }
 public void HandlePut(HttpListenerRequest request, HttpListenerResponse response, Server.RequestData data)
 {
     throw new NotImplementedException();
 }
        private static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
                                                                                          string?subProtocol,
                                                                                          int receiveBufferSize,
                                                                                          TimeSpan keepAliveInterval,
                                                                                          ArraySegment <byte> internalBuffer)
        {
            HttpListenerWebSocketContext?webSocketContext = null;

            try
            {
                // get property will create a new response if one doesn't exist.
                HttpListenerResponse response = context.Response;
                HttpListenerRequest  request  = context.Request;
                ValidateWebSocketHeaders(context);

                string?secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];

                // Optional for non-browser client
                string?origin = request.Headers[HttpKnownHeaderNames.Origin];

                List <string> secWebSocketProtocols = new List <string>();
                string        outgoingSecWebSocketProtocolString;
                bool          shouldSendSecWebSocketProtocolHeader =
                    ProcessWebSocketProtocolHeader(
                        request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
                        subProtocol,
                        out outgoingSecWebSocketProtocolString);

                if (shouldSendSecWebSocketProtocolHeader)
                {
                    secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString);
                    response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol,
                                         outgoingSecWebSocketProtocolString);
                }

                // negotiate the websocket key return value
                string?secWebSocketKey    = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
                string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey);

                response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
                response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
                response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);

                response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
                response.ComputeCoreHeaders();
                ulong hresult = SendWebSocketHeaders(response);
                if (hresult != 0)
                {
                    throw new WebSocketException((int)hresult,
                                                 SR.Format(SR.net_WebSockets_NativeSendResponseHeaders,
                                                           nameof(AcceptWebSocketAsync),
                                                           hresult));
                }

                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.Origin} = {origin}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketVersion} = {secWebSocketVersion}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketKey} = {secWebSocketKey}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketAccept} = {secWebSocketAccept}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {outgoingSecWebSocketProtocolString}");
                }

                await response.OutputStream.FlushAsync().SuppressContextFlow();

                HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream) !;
                Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream.");
                ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode();
                HttpRequestStream requestStream = new HttpRequestStream(context);
                requestStream.SwitchToOpaqueMode();
                WebSocketHttpListenerDuplexStream webSocketStream =
                    new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context);
                WebSocket webSocket = ServerWebSocket.Create(webSocketStream,
                                                             subProtocol,
                                                             receiveBufferSize,
                                                             keepAliveInterval,
                                                             internalBuffer);

                webSocketContext = new HttpListenerWebSocketContext(
                    request.Url !,
                    request.Headers,
                    request.Cookies,
                    context.User !,
                    request.IsAuthenticated,
                    request.IsLocal,
                    request.IsSecureConnection,
                    origin !,
                    secWebSocketProtocols.AsReadOnly(),
                    secWebSocketVersion !,
                    secWebSocketKey !,
                    webSocket);

                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Associate(context, webSocketContext);
                    NetEventSource.Associate(webSocketContext, webSocket);
                }
            }
            catch (Exception ex)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(context, ex);
                }
                throw;
            }

            return(webSocketContext);
        }
Exemple #35
0
    //处理客户端请求
    private void HandleRequest(object ctx)
    {
        HttpListenerContext  context  = ctx as HttpListenerContext;
        HttpListenerResponse response = context.Response;
        HttpListenerRequest  request  = context.Request;

        try
        {
            string rawUrl          = request.RawUrl;
            int    paramStartIndex = rawUrl.IndexOf('?');
            if (paramStartIndex > 0)
            {
                rawUrl = rawUrl.Substring(0, paramStartIndex);
            }
            else if (paramStartIndex == 0)
            {
                rawUrl = "";
            }


            #region 网页请求
            //string InputStream = "";
            using (var streamReader = new StreamReader(request.InputStream))
            {
                //InputStream = streamReader.ReadToEnd();
            }
            string filePath = "";
            if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/")
            {
                filePath = WebHomeDir + "/index.html";                // + directorySeparatorChar + "Index.html";
            }
            else
            {
                filePath = WebHomeDir + rawUrl;                //.Replace("/", directorySeparatorChar);
            }
            if (!File.Exists(filePath))
            {
                HttpPacket packet = HttpPacketFactory.createPacket(rawUrl);
                if (null != packet)
                {
                    packet.handlePacket(ref response, ref request);
                }
                else
                {
                    response.ContentLength64 = 0;
                    response.StatusCode      = 404;
                    response.Abort();
                }
            }
            else
            {
                response.StatusCode = 200;
                string exeName = Path.GetExtension(filePath);
                response.ContentType = GetContentType(exeName);
                FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                int        byteLength = (int)fileStream.Length;
                byte[]     fileBytes  = new byte[byteLength];
                fileStream.Read(fileBytes, 0, byteLength);
                fileStream.Flush();
                fileStream.Dispose();
                response.ContentLength64 = byteLength;
                response.OutputStream.Write(fileBytes, 0, byteLength);
                response.OutputStream.Flush();
            }
            #endregion
        }
        catch (Exception ex)
        {
            UnityUtility.logInfo(typeof(HttpServerManager) + ex.Message);
            response.StatusCode  = 200;
            response.ContentType = "text/plain";
            using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
            {
                writer.WriteLine("接收完成!");
            }
        }
        try
        {
            response.Close();
        }
        catch (Exception ex)
        {
            UnityUtility.logInfo(typeof(HttpServerManager) + ex.Message);
        }
    }
 public void HandlePost(HttpListenerRequest request, HttpListenerResponse response, Server.RequestData data)
 {
     response.StatusCode = 404;
     response.WriteResponse("404 Page Not Found");
 }
Exemple #37
0
		internal ResponseStream (System.IO.Stream stream, HttpListenerResponse response, bool ignore_errors)
		{
			this.response = response;
			this.ignore_errors = ignore_errors;
			this.stream = stream;
		}
Exemple #38
0
        public async Task SetCookie_NullCookie_ThrowsArgumentNullException()
        {
            HttpListenerResponse response = await GetResponse();

            AssertExtensions.Throws <ArgumentNullException>("cookie", () => response.SetCookie(null));
        }
Exemple #39
0
 static void RespondWith(HttpListenerResponse resp, byte[] bytes)
 {
     var outp = resp.OutputStream;
       using (outp) {
     outp.Write(bytes, 0, bytes.Length);
       }
 }
Exemple #40
0
 public static void Respond(HttpListenerContext context, HttpListenerResponse response, bool shouldEndSession, string responseString)
 {
     string responseJson = CreateJsonResponse(shouldEndSession, responseString);
     Console.WriteLine(DateTime.UtcNow + " - " + context.Request.RemoteEndPoint.Address.ToString() + " - " + responseJson);
     byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseJson);
     // Get a response stream and write the response to it.
     response.ContentLength64 = buffer.Length;
     System.IO.Stream output = response.OutputStream;
     output.Write(buffer, 0, buffer.Length);
     // You must close the output stream.
     output.Close();
 }
Exemple #41
0
        private void CheckServer(HttpListenerRequest request, HttpListenerResponse response)
        {
            response.StatusCode = (int)HttpStatusCode.OK;

            SendObject(response, Constants.ServerCheckString);
        }
 public void HandleDelete(HttpListenerRequest request, HttpListenerResponse response)
 {
     throw new NotImplementedException();
 }
Exemple #43
0
        private void SendOrderScheme(HttpListenerRequest request, HttpListenerResponse response)
        {
            var orderScheme = GetOrderSheme();

            SendObject(response, orderScheme);
        }
Exemple #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpResponse"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public HttpResponse(HttpListenerContext context)
 {
     _response = context.Response;
     Cookies   = new CookieCollection(_response.Cookies);
 }
Exemple #45
0
 public static void Respond(HttpListenerContext context, HttpListenerResponse response, bool shouldEndSession)
 {
     Respond(context, response, shouldEndSession, "");
 }
Exemple #46
0
        //函数中的传送的数据有问题,目前仅为测试
        static void Handler()
        {
            DeliveryData deliveryData = new DeliveryData();

            while (true)
            {
                //等待获得客户的请求
                HttpListenerContext context = httpListener.GetContext();
                if (IsOverTime(5000))
                {
                    commonData.InitData();
                    commonData.mapData = GenerateMaps();
                    GenerateReverseIndex();
                    deliveryData.InitData();
                    Console.WriteLine("服务器已经重置");
                }

                #region 状态机,本例中,通过URL传过来的数据只需要时间戳和打击的坐标轴即可
                //防止恶意URL
                string str_timestamp;
                if (context.Request.QueryString["timestamp"] != null)
                {
                    str_timestamp = context.Request.QueryString["timestamp"];
                }
                else
                {
                    continue;
                }
                if (!commonData.list_timestamp.Contains(str_timestamp))
                {
                    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    str_timestamp = ts.TotalMilliseconds.ToString();
                    commonData.list_timestamp.Add(str_timestamp);
                }
                //确定请求发出方
                deliveryData.cur_timestamp = str_timestamp;
                deliveryData.player_idx    = commonData.list_timestamp.IndexOf(str_timestamp);
                if (commonData.list_timestamp.Count >= 2)
                {
                    deliveryData.isPlayerReady = true;
                }
                if (deliveryData.player_idx < 2)//如果此时是玩家的请求
                {
                    if (context.Request.QueryString["mapidx"] != null)
                    {
                        int mapidx = 0;
                        int.TryParse(context.Request.QueryString["mapidx"], out mapidx);
                        if (commonData.mapData[1 - deliveryData.player_idx, mapidx] == MapGridStatus.Blank)
                        {
                            commonData.mapData[1 - deliveryData.player_idx, mapidx] = MapGridStatus.BlankChosen;
                            commonData.list_ready[deliveryData.player_idx]          = false;
                            commonData.list_ready[1 - deliveryData.player_idx]      = true;
                        }
                        else if (commonData.mapData[1 - deliveryData.player_idx, mapidx] == MapGridStatus.Ship)
                        {
                            commonData.mapData[1 - deliveryData.player_idx, mapidx] = MapGridStatus.ShipChosen;
                            SetBlankChosen(1 - deliveryData.player_idx, mapidx);
                            commonData.list_leftShip[1 - deliveryData.player_idx]--;
                            if (commonData.list_leftShip[1 - deliveryData.player_idx] == 0)
                            {
                                deliveryData.isGameOver = true;
                                deliveryData.winner_idx = deliveryData.player_idx;
                            }
                        }
                    }
                    else
                    {
                        deliveryData.isReady = commonData.list_ready[deliveryData.player_idx];
                    }
                }
                else
                {
                    //观众处理
                }

                #endregion

                //刷新数据
                deliveryData.mapData = (MapGridStatus[, ])commonData.mapData.Clone();
                if (deliveryData.player_idx < 2)
                {
                    deliveryData.CleanMapData(1 - deliveryData.player_idx);
                }

                //传回的响应
                HttpListenerResponse response = context.Response;
                last_response = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds;
                //服务端上显示连接记录
                Console.WriteLine("player: {0} linked, id: {1}", context.Request.Url, commonData.list_timestamp[deliveryData.player_idx]);
                //传输数据部分
                byte[] buffer = SerializeHelper.SerializeToBinary(deliveryData);
                using (Stream output = response.OutputStream)
                {
                    output.Write(buffer, 0, buffer.Length);
                }
            }
        }
 public void CopyFrom(HttpListenerResponse templateResponse)
 {
     headers.Clear ();
     headers.Add (templateResponse.headers);
     content_length = templateResponse.content_length;
     status_code = templateResponse.status_code;
     status_description = templateResponse.status_description;
     keep_alive = templateResponse.keep_alive;
     version = templateResponse.version;
 }
	// Methods
	public void CopyFrom(HttpListenerResponse templateResponse) {}