Paihikara matatau, tono-kaitono ranei i runga i te anga C# .Net

urunga

I timata katoa i te wa i kii mai tetahi hoa mahi kia mahia e au tetahi ratonga paetukutuku iti. Ko te whakaaro he ahua rite ki te tinder, engari mo te waahi IT. He tino ngawari te mahi, ka rehita koe, whakakiia he kotaha ka haere ki te kaupapa matua, ara, te kimi i tetahi kaikorero me te whakawhanui i o hononga me te mohio hou.

I konei me huri kee ahau me te korero iti mo au ake nei, kia marama ake ai te take i mahia e au enei mahi whanaketanga.

I tenei wa ka mau ahau i te tuunga o te Kaihanga Hangarau i roto i te taiwhanga keemu, ko taku wheako kaupapa C# i ahu mai i runga i te tuhi tuhinga me nga taputapu mo te Unity, a, hei taapiri atu ki tenei, ko te hanga mono mo nga mahi taumata-iti me nga taputapu phi. I waho o tenei ao, kaore ano au i whiriwhiri, katahi ka puta mai he waahi penei.

Wāhanga 1. Tāpare Prototyping

I te whakatau he aha te ahua o tenei ratonga, ka tiimata ahau ki te rapu whiringa mo te whakatinanatanga. Ko te huarahi ngawari ko te kimi i tetahi momo otinga kua oti te hanga, he rite ki te ruru i runga i te ao, ka taea e koe te kumea i a maatau miihini me te whakatakoto i nga mea katoa mo te whakahee a te iwi.
Engari ehara tenei i te mea whakamere, kaore au i kite i tetahi wero me te mohio ki tenei, na reira i timata ahau ki te ako i nga hangarau tukutuku me nga tikanga mo te taunekeneke ki a raatau.

I timata te rangahau ma te tirotiro i nga tuhinga me nga tuhinga mo C # .Net. I konei ka kitea e au nga momo huarahi hei whakatutuki i te mahi. He maha nga tikanga mo te taunekeneke me te whatunga, mai i nga otinga tino rite ki te ASP.Net, ki nga ratonga Azure ranei, ki te whakahaere i te taunekeneke me nga hononga TcpHttp.

I te mahi tuatahi ki te ASP, ka whakakorehia e au, ki taku whakaaro he tino uaua te whakatau mo ta maatau ratonga. E kore matou e whakamahi i te hautoru o nga kaha o tenei turanga, no reira i haere tonu taku rapu. I puta te whiringa i waenga i te TCP me te Http client-server. I konei, i runga i a Habré, i kite ahau i tetahi tuhinga mo tūmau miro maha, ka kohia, ka whakamatauhia e au, ka whakatau ahau ki te aro ki te taunekeneke me nga hononga TCP, mo etahi take i whakaaro ahau kaore e whakaaetia e http ahau ki te hanga i tetahi otinga whakawhiti.

Ko te putanga tuatahi o te tūmau ko te whakahaere i nga hononga, te tuku i nga ihirangi wharangi paetukutuku tuuturu, me te whakauru i te papaunga raraunga kaiwhakamahi. Na mo te timatanga, i whakatau ahau ki te hanga i tetahi mahi mo te mahi me te papanga, kia taea ai e au te here i te tukatuka tono i runga i te phi me te iOS i konei.

Anei etahi waehere
Ko te miro matua e whakaae ana ki nga kaihoko i roto i te kopikopiko mutunga kore:

using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace ClearServer
{

    class Server
    {
        TcpListener Listener;
        public Server(int Port)
        {
            Listener = new TcpListener(IPAddress.Any, Port);
            Listener.Start();

            while (true)
            {
                TcpClient Client = Listener.AcceptTcpClient();
                Thread Thread = new Thread(new ParameterizedThreadStart(ClientThread));
                Thread.Start(Client);
            }
        }

        static void ClientThread(Object StateInfo)
        {
            new Client((TcpClient)StateInfo);
        }

        ~Server()
        {
            if (Listener != null)
            {
                Listener.Stop();
            }
        }

        static void Main(string[] args)
        {
            DatabaseWorker sqlBase = DatabaseWorker.GetInstance;

            new Server(80);
        }
    }
}

Ko te kaihautu kiritaki ake:

using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace ClearServer
{
    class Client
    {


        public Client(TcpClient Client)
        {

            string Message = "";
            byte[] Buffer = new byte[1024];
            int Count;
            while ((Count = Client.GetStream().Read(Buffer, 0, Buffer.Length)) > 0)
            {
                Message += Encoding.UTF8.GetString(Buffer, 0, Count);

                if (Message.IndexOf("rnrn") >= 0 || Message.Length > 4096)
                {
                    Console.WriteLine(Message);
                    break;
                }
            }

            Match ReqMatch = Regex.Match(Message, @"^w+s+([^s?]+)[^s]*s+HTTP/.*|");
            if (ReqMatch == Match.Empty)
            {
                ErrorWorker.SendError(Client, 400);
                return;
            }
            string RequestUri = ReqMatch.Groups[1].Value;
            RequestUri = Uri.UnescapeDataString(RequestUri);
            if (RequestUri.IndexOf("..") >= 0)
            {
                ErrorWorker.SendError(Client, 400);
                return;
            }
            if (RequestUri.EndsWith("/"))
            {
                RequestUri += "index.html";
            }

            string FilePath =

quot;D:/Web/TestSite{RequestUri}";

if (!File.Exists(FilePath))
{
ErrorWorker.SendError(Client, 404);
return;
}

string Extension = RequestUri.Substring(RequestUri.LastIndexOf('.'));

string ContentType = "";

switch (Extension)
{
case ".htm":
case ".html":
ContentType = "text/html";
break;
case ".css":
ContentType = "text/css";
break;
case ".js":
ContentType = "text/javascript";
break;
case ".jpg":
ContentType = "image/jpeg";
break;
case ".jpeg":
case ".png":
case ".gif":
ContentType =


quot;image/{Extension.Substring(1)}";
break;
default:
if (Extension.Length > 1)
{
ContentType =


quot;application/{Extension.Substring(1)}";
}
else
{
ContentType = "application/unknown";
}
break;
}

FileStream FS;
try
{
FS = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception)
{
ErrorWorker.SendError(Client, 500);
return;
}

string Headers =


quot;HTTP/1.1 200 OKnContent-Type: {ContentType}nContent-Length: {FS.Length}nn";
byte[] HeadersBuffer = Encoding.ASCII.GetBytes(Headers);
Client.GetStream().Write(HeadersBuffer, 0, HeadersBuffer.Length);

while (FS.Position < FS.Length)
{
Count = FS.Read(Buffer, 0, Buffer.Length);
Client.GetStream().Write(Buffer, 0, Count);
}

FS.Close();
Client.Close();
}
}
}

Na ko te papaunga raraunga tuatahi i hangaia i runga i te SQL rohe:

using System;
using System.Data.Linq;
namespace ClearServer
{
    class DatabaseWorker
    {

        private static DatabaseWorker instance;

        public static DatabaseWorker GetInstance
        {
            get
            {
                if (instance == null)
                    instance = new DatabaseWorker();
                return instance;
            }
        }


        private DatabaseWorker()
        {
            string connectionStr = databasePath;
            using (DataContext db = new DataContext(connectionStr))
            {
                Table<User> users = db.GetTable<User>();
                foreach (var item in users)
                {
                    Console.WriteLine(

quot;{item.login} {item.password}");
}
}
}
}
}

Ka taea e koe te kite, he rereke te rereke o tenei putanga mai i te mea kei roto i te tuhinga. Inaa, ko te utaina noa o nga wharangi mai i te kopaki i runga i te rorohiko me te papaaarangi i tapirihia ki konei (na te ara, kaore i mahi i tenei putanga, na te he o te hoahoa hononga).

Upoko 2

I muri i te whakamatautau i te tūmau, ka tae mai ahau ki te whakatau he pai tenei otinga (kaipahua: kahore), mo ta maatau ratonga, no reira ka timata te kaupapa ki te whiwhi arorau.
Ma te hikoi, ka tiimata te puta mai o nga waahanga hou, ka tipu te mahi o te tūmau. Kua whiwhi te tūmau i te rohe whakamātautau me te whakamunatanga hononga ssl.

He iti ake te waehere e whakaatu ana i te arorau o te tūmau me te tukatuka o nga kiritaki
He putanga whakahou o te tūmau, tae atu ki te whakamahi tiwhikete.

using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Policy;
using System.Threading;


namespace ClearServer
{

    sealed class Server
    {
        readonly bool ServerRunning = true;
        readonly TcpListener sslListner;
        public static X509Certificate serverCertificate = null;
        Server()
        {
            serverCertificate = X509Certificate.CreateFromSignedFile(@"C:sslitinder.online.crt");
            sslListner = new TcpListener(IPAddress.Any, 443);
            sslListner.Start();
            Console.WriteLine("Starting server.." + serverCertificate.Subject + "n" + Assembly.GetExecutingAssembly().Location);
            while (ServerRunning)
            {
                TcpClient SslClient = sslListner.AcceptTcpClient();
                Thread SslThread = new Thread(new ParameterizedThreadStart(ClientThread));
                SslThread.Start(SslClient);
            }
            
        }
        static void ClientThread(Object StateInfo)
        {
            new Client((TcpClient)StateInfo);
        }

        ~Server()
        {
            if (sslListner != null)
            {
                sslListner.Stop();
            }
        }

        public static void Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                Console.WriteLine("Switching another domain");
                new AppDomainSetup
                {
                    ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
                };
                var current = AppDomain.CurrentDomain;
                var strongNames = new StrongName[0];
                var domain = AppDomain.CreateDomain(
                    "ClearServer", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
            }
            new Server();
        }
    }
}

Me te kaikawe kaihoko hou me te whakamanatanga ma te ssl:

using ClearServer.Core.Requester;
using System;
using System.Net.Security;
using System.Net.Sockets;

namespace ClearServer
{
    public class Client
    {
        public Client(TcpClient Client)
        {
            SslStream SSlClientStream = new SslStream(Client.GetStream(), false);
            try
            {
                SSlClientStream.AuthenticateAsServer(Server.serverCertificate, clientCertificateRequired: false, checkCertificateRevocation: true);
            }
            catch (Exception e)
            {
                Console.WriteLine(
                    "---------------------------------------------------------------------n" +


quot;|{DateTime.Now:g}n|------------n|{Client.Client.RemoteEndPoint}n|------------n|Exception: {e.Message}n|------------n|Authentication failed - closing the connection.n" +
"---------------------------------------------------------------------n");
SSlClientStream.Close();
Client.Close();
}
new RequestContext(SSlClientStream, Client);
}

}
}

Engari i te mea ka mahi anake te tūmau i runga i te hononga TCP, me hanga he kōwae e mohio ana ki te horopaki tono. I whakatau ahau he pai ki konei he parser ka wehe i te tono mai i te kiritaki ki nga waahanga motuhake ka taea e au te taunekeneke kia hoatu ki te kaihoko nga whakautu e tika ana.

poroporoaki

using ClearServer.Core.UserController;
using ReServer.Core.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace ClearServer.Core.Requester
{
    public class RequestContext
    {
        public string Message = "";
        private readonly byte[] buffer = new byte[1024];
        public string RequestMethod;
        public string RequestUrl;
        public User RequestProfile;
        public User CurrentUser = null;
        public List<RequestValues> HeadersValues;
        public List<RequestValues> FormValues;
        private TcpClient TcpClient;

        private event Action<SslStream, RequestContext> OnRead = RequestHandler.OnHandle;

        DatabaseWorker databaseWorker = new DatabaseWorker();

        public RequestContext(SslStream ClientStream, TcpClient Client)
        {

            this.TcpClient = Client;
            try
            {
                ClientStream.BeginRead(buffer, 0, buffer.Length, ClientRead, ClientStream);
            }
            catch { return; }
        }
        private void ClientRead(IAsyncResult ar)
        {
            SslStream ClientStream = (SslStream)ar.AsyncState;

            if (ar.IsCompleted)
            {
                Message = Encoding.UTF8.GetString(buffer);
                Message = Uri.UnescapeDataString(Message);
                Console.WriteLine(

quot;n{DateTime.Now:g} Client IP:{TcpClient.Client.RemoteEndPoint}n{Message}");
RequestParse();
HeadersValues = HeaderValues();
FormValues = ContentValues();
UserParse();
ProfileParse();
OnRead?.Invoke(ClientStream, this);
}
}

private void RequestParse()
{
Match methodParse = Regex.Match(Message, @"(^w+)s+([^s?]+)[^s]*s+HTTP/.*|");
RequestMethod = methodParse.Groups[1].Value.Trim();
RequestUrl = methodParse.Groups[2].Value.Trim();
}
private void UserParse()
{
string cookie;
try
{
if (HeadersValues.Any(x => x.Name.Contains("Cookie")))
{
cookie = HeadersValues.FirstOrDefault(x => x.Name.Contains("Cookie")).Value;
try
{
CurrentUser = databaseWorker.CookieValidate(cookie);
}
catch { }
}
}
catch { }

}
private List<RequestValues> HeaderValues()
{
var values = new List<RequestValues>();
var parse = Regex.Matches(Message, @"(.*?): (.*?)n");
foreach (Match match in parse)
{
values.Add(new RequestValues()
{
Name = match.Groups[1].Value.Trim(),
Value = match.Groups[2].Value.Trim()
});
}
return values;
}

private void ProfileParse()
{
if (RequestUrl.Contains("@"))
{
RequestProfile = databaseWorker.FindUser(RequestUrl.Substring(2));
RequestUrl = "/profile";
}
}
private List<RequestValues> ContentValues()
{
var values = new List<RequestValues>();
var output = Message.Trim('n').Split().Last();
var parse = Regex.Matches(output, @"([^&].*?)=([^&]*b)");
foreach (Match match in parse)
{
values.Add(new RequestValues()
{
Name = match.Groups[1].Value.Trim(),
Value = match.Groups[2].Value.Trim().Replace('+', ' ')
});
}
return values;
}
}
}

Ko tona ngako kei roto i te meka na te awhina o nga korero auau ki te wawahi i te tono ki etahi waahanga. Ka whiwhi matou i te karere mai i te kiritaki, tohua te rarangi tuatahi, kei roto te tikanga me te tono url. Na ka panuihia e matou nga pane, ka peia e matou ki roto i te huinga o te ahua HeaderName = Ihirangi, ka kitea hoki, mehemea he, nga ihirangi e whai ana (hei tauira, querystring) ka peia ano e matou ki roto i te raupapa rite. I tua atu, ka kitea e te parser mena kua whakamanahia te kaihoko o naianei me te penapena i ana raraunga. Ko nga tono katoa mai i nga kaihoko whai mana kei roto he tohu whakamana, kei te rongoa i roto i nga pihikete, na reira ka taea te wehe i etahi atu arorau mahi mo nga momo kaihoko e rua ka hoatu ki a raatau nga whakautu tika.

Ana, he ahua iti, ataahua e tika ana kia nekehia ki roto i tetahi waahanga motuhake, ka huri i nga tono penei i te "site.com/@UserName" ki nga wharangi kaiwhakamahi kua hangaia. I muri i te tukatuka i te tono, ka uru mai nga waahanga e whai ake nei.

Upoko 3. Te whakauru i te kakau, whakahinuhinu te mekameka

Kia oti te mahi parser, ka uru mai te kaihautu ki te takaro, ka hoatu etahi atu tohutohu ki te tūmau me te wehe i te mana whakahaere kia rua nga wahanga.

kaihautu ngawari

using ClearServer.Core.UserController;
using System.Net.Security;
namespace ClearServer.Core.Requester
{
    public class RequestHandler
    {
        public static void OnHandle(SslStream ClientStream, RequestContext context)
        {

            if (context.CurrentUser != null)
            {
                new AuthUserController(ClientStream, context);
            }
            else 
            {
                new NonAuthUserController(ClientStream, context);
            };
        }
    }
}

Inaa, kotahi anake te haki mo te whakamanatanga a te kaiwhakamahi, ka mutu ka timata te tukatuka tono.

Kaiwhakahaere Kiritaki
Mena kaore i te whakamanahia te kaiwhakamahi, mo ia anake te mahi i runga i te whakaaturanga o nga whaarangi kaiwhakamahi me te matapihi rehitatanga whakamana. He rite tonu te ahua o te waehere mo te kaiwhakamahi whai mana, no reira kare au e kite i te take hei taarua.

Kaiwhakamahi kore mana

using ClearServer.Core.Requester;
using System.IO;
using System.Net.Security;

namespace ClearServer.Core.UserController
{
    internal class NonAuthUserController
    {
        private readonly SslStream ClientStream;
        private readonly RequestContext Context;
        private readonly WriteController WriteController;
        private readonly AuthorizationController AuthorizationController;

        private readonly string ViewPath = "C:/Users/drdre/source/repos/ClearServer/View";

        public NonAuthUserController(SslStream clientStream, RequestContext context)
        {
            this.ClientStream = clientStream;
            this.Context = context;
            this.WriteController = new WriteController(clientStream);
            this.AuthorizationController = new AuthorizationController(clientStream, context);
            ResourceLoad();
        }

        void ResourceLoad()
        {
            string[] blockextension = new string[] {"cshtml", "html", "htm"};
            bool block = false;
            foreach (var item in blockextension)
            {
                if (Context.RequestUrl.Contains(item))
                {
                    block = true;
                    break;
                }
            }
            string FilePath = "";
            string Header = "";
            var RazorController = new RazorController(Context, ClientStream);
            
            switch (Context.RequestMethod)
            {
                case "GET":
                    switch (Context.RequestUrl)
                    {
                        case "/":
                            FilePath = ViewPath + "/loginForm.html";
                            Header =

quot;HTTP/1.1 200 OKnContent-Type: text/html";
WriteController.DefaultWriter(Header, FilePath);
break;
case "/profile":
RazorController.ProfileLoader(ViewPath);
break;
default:
//в данном блоке кода происходит отсечение запросов к серверу по прямому адресу страницы вида site.com/page.html
if (!File.Exists(ViewPath + Context.RequestUrl) | block)
{
RazorController.ErrorLoader(404);

}
else if (Path.HasExtension(Context.RequestUrl) && File.Exists(ViewPath + Context.RequestUrl))
{
Header = WriteController.ContentType(Context.RequestUrl);
FilePath = ViewPath + Context.RequestUrl;
WriteController.DefaultWriter(Header, FilePath);
}
break;
}
break;

case "POST":
AuthorizationController.MethodRecognizer();
break;

}

}

}
}

A ko te tikanga, me whiwhi te kaiwhakamahi i etahi ihirangi o nga wharangi, na mo nga whakautu kei reira te waahanga e whai ake nei, ko te kawenga mo te whakautu ki te tono rauemi.

KaituhiKaiwhakahaere

using System;
using System.IO;
using System.Net.Security;
using System.Text;

namespace ClearServer.Core.UserController
{
    public class WriteController
    {
        SslStream ClientStream;
        public WriteController(SslStream ClientStream)
        {
            this.ClientStream = ClientStream;
        }

        public void DefaultWriter(string Header, string FilePath)
        {
            FileStream fileStream;
            try
            {
                fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                Header =

quot;{Header}nContent-Length: {fileStream.Length}nn";
ClientStream.Write(Encoding.UTF8.GetBytes(Header));
byte[] response = new byte[fileStream.Length];
fileStream.BeginRead(response, 0, response.Length, OnFileRead, response);
}
catch { }
}

public string ContentType(string Uri)
{
string extension = Path.GetExtension(Uri);
string Header = "HTTP/1.1 200 OKnContent-Type:";
switch (extension)
{
case ".html":
case ".htm":
return


quot;{Header} text/html";
case ".css":
return


quot;{Header} text/css";
case ".js":
return


quot;{Header} text/javascript";
case ".jpg":
case ".jpeg":
case ".png":
case ".gif":
return


quot;{Header} image/{extension}";
default:
if (extension.Length > 1)
{
return


quot;{Header} application/" + extension.Substring(1);
}
else
{
return


quot;{Header} application/unknown";
}
}
}

public void OnFileRead(IAsyncResult ar)
{
if (ar.IsCompleted)
{
var file = (byte[])ar.AsyncState;
ClientStream.BeginWrite(file, 0, file.Length, OnClientSend, null);
}
}

public void OnClientSend(IAsyncResult ar)
{
if (ar.IsCompleted)
{
ClientStream.Close();
}
}
}

Engari hei whakaatu ki te kaiwhakamahi tana korero me nga korero a etahi atu kaiwhakamahi, i whakatau ahau ki te whakamahi i a RazorEngine, he waahanga ranei. Kei roto hoki te whakahaere i nga tono kino me te tuku i te waehere hapa e tika ana.

HeuKaiwhakahaere

using ClearServer.Core.Requester;
using RazorEngine;
using RazorEngine.Templating;
using System;
using System.IO;
using System.Net;
using System.Net.Security;

namespace ClearServer.Core.UserController
{
    internal class RazorController
    {
        private RequestContext Context;
        private SslStream ClientStream;
        dynamic PageContent;


        public RazorController(RequestContext context, SslStream clientStream)
        {
            this.Context = context;
            this.ClientStream = clientStream;

        }

        public void ProfileLoader(string ViewPath)
        {
            string Filepath = ViewPath + "/profile.cshtml";
            if (Context.RequestProfile != null)
            {
                if (Context.CurrentUser != null && Context.RequestProfile.login == Context.CurrentUser.login)
                {
                    try
                    {
                        PageContent = new { isAuth = true, Name = Context.CurrentUser.name, Login = Context.CurrentUser.login, Skills = Context.CurrentUser.skills };
                        ClientSend(Filepath, Context.CurrentUser.login);
                    }
                    catch (Exception e) { Console.WriteLine(e); }

                }
                else
                {
                    try
                    {
                        PageContent = new { isAuth = false, Name = Context.RequestProfile.name, Login = Context.RequestProfile.login, Skills = Context.RequestProfile.skills };
                        ClientSend(Filepath, "PublicProfile:"+ Context.RequestProfile.login);
                    }
                    catch (Exception e) { Console.WriteLine(e); }
                }
            }
            else
            {
                ErrorLoader(404);
            }


        }

        public void ErrorLoader(int Code)
        {
            try
            {
                PageContent = new { ErrorCode = Code, Message = ((HttpStatusCode)Code).ToString() };
                string ErrorPage = "C:/Users/drdre/source/repos/ClearServer/View/Errors/ErrorPage.cshtml";
                ClientSend(ErrorPage, Code.ToString());
            }
            catch { }

        }

        private void ClientSend(string FilePath, string Key)
        {
            var template = File.ReadAllText(FilePath);
            var result = Engine.Razor.RunCompile(template, Key, null, (object)PageContent);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result);
            ClientStream.BeginWrite(buffer, 0, buffer.Length, OnClientSend, ClientStream);
        }

        private void OnClientSend(IAsyncResult ar)
        {
            if (ar.IsCompleted)
            {
                ClientStream.Close();
            }
        }
    }
}

A ko te tikanga, kia mahi ai te manatoko o nga kaiwhakamahi whai mana, me whakamanahia. Ka taunekeneke te kōwae whakamana me te pātengi raraunga. Ko nga raraunga i riro mai i nga puka kei runga i te waahi ka tohatohahia mai i te horopaki, ka tiakina te kaiwhakamahi ka whiwhi pihikete me te uru atu ki te ratonga hei utu.

Kōwae whakamana

using ClearServer.Core.Cookies;
using ClearServer.Core.Requester;
using ClearServer.Core.Security;
using System;
using System.Linq;
using System.Net.Security;
using System.Text;

namespace ClearServer.Core.UserController
{
    internal class AuthorizationController
    {
        private SslStream ClientStream;
        private RequestContext Context;
        private UserCookies cookies;
        private WriteController WriteController;
        DatabaseWorker DatabaseWorker;
        RazorController RazorController;
        PasswordHasher PasswordHasher;
        public AuthorizationController(SslStream clientStream, RequestContext context)
        {
            ClientStream = clientStream;
            Context = context;
            DatabaseWorker = new DatabaseWorker();
            WriteController = new WriteController(ClientStream);
            RazorController = new RazorController(context, clientStream);
            PasswordHasher = new PasswordHasher();
        }

        internal void MethodRecognizer()
        {
            if (Context.FormValues.Count == 2 && Context.FormValues.Any(x => x.Name == "password")) Authorize();
            else if (Context.FormValues.Count == 3 && Context.FormValues.Any(x => x.Name == "regPass")) Registration();
            else
            {
                RazorController.ErrorLoader(401);
            }
        }

        private void Authorize()
        {
            var values = Context.FormValues;
            var user = new User()
            {
                login = values[0].Value,
                password = PasswordHasher.PasswordHash(values[1].Value)
            };
            user = DatabaseWorker.UserAuth(user);
            if (user != null)
            {
                cookies = new UserCookies(user.login, user.password);
                user.cookie = cookies.AuthCookie;
                DatabaseWorker.UserUpdate(user);
                var response = Encoding.UTF8.GetBytes(

quot;HTTP/1.1 301 Moved PermanentlynLocation: /@{user.login}nSet-Cookie: {cookies.AuthCookie}; Expires={DateTime.Now.AddDays(2):R}; Secure; HttpOnlynn");
ClientStream.BeginWrite(response, 0, response.Length, WriteController.OnClientSend, null);

}
else
{
RazorController.ErrorLoader(401);

}
}

private void Registration()
{
var values = Context.FormValues;
var user = new User()
{
name = values[0].Value,
login = values[1].Value,
password = PasswordHasher.PasswordHash(values[2].Value),
};
cookies = new UserCookies(user.login, user.password);
user.cookie = cookies.AuthCookie;
if (DatabaseWorker.LoginValidate(user.login))
{
Console.WriteLine("User ready");
Console.WriteLine(


quot;{user.password} {user.password.Trim().Length}");
DatabaseWorker.UserRegister(user);
var response = Encoding.UTF8.GetBytes(


quot;HTTP/1.1 301 Moved PermanentlynLocation: /@{user.login}nSet-Cookie: {user.cookie}; Expires={DateTime.Now.AddDays(2):R}; Secure; HttpOnlynn");
ClientStream.BeginWrite(response, 0, response.Length, WriteController.OnClientSend, null);
}
else
{
RazorController.ErrorLoader(401);
}
}
}
}

A koinei te ahua o te papaunga raraunga:

Pātengi Raraunga

using ClearServer.Core.UserController;
using System;
using System.Data.Linq;
using System.Linq;

namespace ClearServer
{
    class DatabaseWorker
    {

        private readonly Table<User> users = null;
        private readonly DataContext DataBase = null;
        private const string connectionStr = @"путькбазе";

        public DatabaseWorker()
        {
            DataBase = new DataContext(connectionStr);
            users = DataBase.GetTable<User>();
        }

        public User UserAuth(User User)
        {
            try
            {
                var user = users.SingleOrDefault(t => t.login.ToLower() == User.login.ToLower() && t.password == User.password);
                if (user != null)
                    return user;
                else
                    return null;
            }
            catch (Exception)
            {
                return null;
            }

        }

        public void UserRegister(User user)
        {
            try
            {
                users.InsertOnSubmit(user);
                DataBase.SubmitChanges();
                Console.WriteLine(

quot;User{user.name} with id {user.uid} added");
foreach (var item in users)
{
Console.WriteLine(item.login + "n");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}

}

public bool LoginValidate(string login)
{
if (users.Any(x => x.login.ToLower() == login.ToLower()))
{
Console.WriteLine("Login already exists");
return false;
}
return true;
}
public void UserUpdate(User user)
{
var UserToUpdate = users.FirstOrDefault(x => x.uid == user.uid);
UserToUpdate = user;
DataBase.SubmitChanges();
Console.WriteLine(


quot;User {UserToUpdate.name} with id {UserToUpdate.uid} updated");
foreach (var item in users)
{
Console.WriteLine(item.login + "n");
}
}
public User CookieValidate(string CookieInput)
{
User user = null;
try
{
user = users.SingleOrDefault(x => x.cookie == CookieInput);
}
catch
{
return null;
}
if (user != null) return user;
else return null;
}
public User FindUser(string login)
{
User user = null;
try
{
user = users.Single(x => x.login.ToLower() == login.ToLower());
if (user != null)
{
return user;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
}
}


Na ka mahi nga mea katoa penei i te karaka, te whakamanatanga me te mahi rehitatanga, ko te iti rawa o nga mahi o te uru ki te ratonga kua waatea kua tae ki te waa ki te tuhi tono me te here i nga mea katoa me nga mahi matua e mahia ai nga mea katoa.

Upoko 4

Hei whakaiti i nga utu mahi mo te tuhi i nga tono e rua mo nga papahanga e rua, ka whakatau ahau ki te hanga i tetahi papa-whakawhiti i runga i te Xamarin.Forms. Ano, whakawhetai ki te meka kei roto i te C #. I te hanga i tetahi tono whakamatautau ka tukuna noa nga raraunga ki te kaimau, ka oma ahau ki tetahi waa whakamere. Mo te tono mai i te taputapu, mo te ngahau, i whakatinanahia e ahau ki runga i te HttpClient ka maka ki runga i te tūmau HttpRequestMessage kei roto nga raraunga mai i te puka whakamana i te whakatakotoranga json. Ma te kore e tumanako ki tetahi mea, i whakatuwherahia e ahau te raarangi tūmau ka kite i tetahi tono mai i te taputapu me nga raraunga katoa kei reira. Maamaa te porangi, te mohio ki nga mea katoa i mahia i roto i nga wiki e 3 kua hipa o te ahiahi pouri. Hei tirotiro i te tika o nga raraunga kua tukuna, i whakaemihia e ahau he tūmau whakamatautau i runga i te HttpListner. I te mea kua tae mai te tono e whai ake nei, ka wehea e au i roto i nga rarangi waehere e rua, ka whiwhi raraunga KeyValuePair mai i te puka. I whakaitihia te paahi patai ki nga rarangi e rua.

I timata ahau ki te whakamatautau, kaore i whakahuahia i mua, engari i runga i te kaimau o mua ka whakatinanahia e ahau he korerorero i hangaia i runga i nga paetukutuku. He pai te mahi, engari ko te tino kaupapa o te taunekeneke ma te Tcp he pouri, he nui rawa atu te mahi hei hanga tika i te taunekeneke o nga kaiwhakamahi e rua me te takiuru o nga reta. Kei roto i tenei ko te panui i te tono mo te whakawhiti hononga me te kohikohi i te whakautu ma te whakamahi i te kawa RFC 6455. Na reira, i roto i te tūmau whakamatautau, i whakatau ahau ki te hanga i tetahi hononga tukutuku ngawari. Maama mo te painga.

Hononga korero

 private static async void HandleWebsocket(HttpListenerContext context)
        {
            var socketContext = await context.AcceptWebSocketAsync(null);
            var socket = socketContext.WebSocket;
            Locker.EnterWriteLock();
            try
            {
                Clients.Add(socket);
            }
            finally
            {
                Locker.ExitWriteLock();
            }

            while (true)
            {
                var buffer = new ArraySegment<byte>(new byte[1024]);
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                var str = Encoding.Default.GetString(buffer);
                Console.WriteLine(str);

                for (int i = 0; i < Clients.Count; i++)
                {
                    WebSocket client = Clients[i];

                    try
                    {
                        if (client.State == WebSocketState.Open)
                        {
                            
                            await client.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        Locker.EnterWriteLock();
                        try
                        {
                            Clients.Remove(client);
                            i--;
                        }
                        finally
                        {
                            Locker.ExitWriteLock();
                        }
                    }
                }
            }
        }

Na ka whai hua. Na te tūmau tonu i whakarite te hononga, i hanga he kī whakautu. Kaore au i tika ki te whirihora wehe i te rehitatanga o te kaitoro ma te ssl, kua nui noa atu te punaha kua whakauruhia he tiwhikete ki runga i te tauranga e hiahiatia ana.

I te taha o te taputapu me te taha o te waahi, e rua nga kaihoko i whakawhiti karere, kua tuhia katoatia tenei. Karekau he kaiporoporo nui e whakaroa ana i te tūmau, karekau he mea e hiahiatia ana. Kua whakahekehia te wa whakautu mai i te 200ms ki te 40-30ms. Na ka tae mai ahau ki te whakatau tika anake.

Paihikara matatau, tono-kaitono ranei i runga i te anga C# .Net

Makahia te whakatinanatanga tūmau o nāianei i runga i Tcp me te tuhi ano i nga mea katoa i raro i te Http. Inaianei ko te kaupapa kei te waahi o te hoahoa ano, engari i runga i nga tikanga rereke o te taunekeneke. Ko te mahi o nga taputapu me te papanga he tukutahi me te patuiro me te whakaaro noa, me te rereke anake kaore nga taputapu e hiahia ki te whakaputa i nga wharangi html.

mutunga

"Kare koe e mohio ki te whiti, kaua e werohia to mahunga ki te wai" Ki taku whakaaro, i mua i te tiimata o te mahi, me whakamarama ake e au nga whainga me nga whainga, me te ruku ki te ako i nga hangarau me nga tikanga e tika ana mo te whakatinanatanga ki nga tini kaihoko. Kua tata oti te kaupapa, engari tera pea ka hoki mai ano ahau ki te korero mo te ahua o taku weriweri i etahi mea. He maha nga mea i akohia e au i te wa o te whakawhanaketanga, engari he maha ano nga mea hei ako mo nga ra kei mua. Mena kua panui koe i tenei tawhiti, ka mihi mo te panui.

Source: will.com