Example #1
0
        static void SimpleParallelServe(Socket socket, RequestProcessor processor)
        {
            var tasks = Enumerable.Repeat(new Func <Task>(() => Task.Run(() =>
            {
                Console.WriteLine($"thread {Thread.CurrentThread.ManagedThreadId} initialized!");
                SimpleServe(socket, processor);
            })), threadNumber).Select(f => f()).ToArray();

            Task.WaitAll(tasks);
        }
Example #2
0
 static async void AsyncServe(Socket socket, RequestProcessor processor)
 {
     // var taskCompletion = new TaskCompletionSource<object>();
     while (true)
     {
         var conn     = socket.Accept();
         var clientIp = (IPEndPoint)conn.RemoteEndPoint;
         int connId   = connCnt++;
         Logger.Log($"----------thread {Thread.CurrentThread.ManagedThreadId}: connection {connId} established: {clientIp.Address}");
         AsyncProcess(conn, connId, processor);
     }
     //await taskCompletion.Task;
 }
Example #3
0
        public void Start()
        {
            var reqpro = new RequestProcessor();

            _listener.Start();

            while (true)
            {
                try
                {
                    HttpListenerContext  context  = _listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;
                    //Создаем ответ
                    Stream       inputStream = request.InputStream;
                    Encoding     encoding    = request.ContentEncoding;
                    StreamReader reader      = new StreamReader(inputStream, encoding);
                    var          requestBody = reader.ReadToEnd();

                    Console.WriteLine("{0} request was caught: {1}",
                                      request.HttpMethod, request.Url);
                    var    urlParts = request.Url.AbsolutePath.Split('/');
                    string msg;

                    try
                    {
                        if (urlParts[1] != "register")
                        {
                            DbProcessor.CheckAuth(urlParts[2], urlParts[3]);
                        }
                        msg = reqpro.GetResponseData(request.HttpMethod, urlParts, requestBody);
                        response.StatusCode = (int)HttpStatusCode.OK;
                    }
                    catch (Exception e)
                    {
                        msg = "Request error! " + e.Message;
                        Console.WriteLine(msg);
                        response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }


                    byte[] b = Encoding.UTF8.GetBytes(msg);
                    context.Response.ContentLength64 = b.Length;
                    context.Response.OutputStream.Write(b, 0, b.Length);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Net trouble\r\n" + exception.Message);
                }
            }
        }
Example #4
0
        static async void AsyncProcess(Socket conn, int connId, RequestProcessor processor)
        {
            try
            {
                var st = DateTime.Now;
                var et = st + TimeSpan.FromSeconds(300);
                while (DateTime.Now < et)
                {
                    var result = await conn.ReceiveAsync();

                    if (result.Count == 0)
                    {
                        break;
                    }
                    //var result = new byte[1024];
                    //conn.Receive(result, 0, 1024, SocketFlags.None);
                    var response = await Process(result, connId, processor);

                    await conn.SendAsync(response.Header.Concat(response.Body).ToArray());

                    /*socket.BeginAccept(async ar => {
                     *  taskCompletion.SetResult(null);
                     *  var conn = socket.EndAccept(ar);
                     *  try
                     *  {
                     *      //Console.WriteLine("start processing incoming request---------------------------------");
                     *      var response = Process(conn, RequestProcessors.Echo);
                     *      await conn.SendAsync(response.Header);
                     *      await conn.SendAsync(response.Body);
                     *  }
                     *  finally
                     *  {
                     *      conn.Close();
                     *      //Console.WriteLine("done--------------------------------------------------------------\r\n\r\n");
                     *  }
                     * }, null);//*/
                }
            }
            finally
            {
                Logger.Log($"----------connection {connId} closed!");
                conn.Close();
            }
        }
Example #5
0
            public Server(int portNum, ServeFunc serveFunc, RequestProcessor processor)
            {
                socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    IPEndPoint ep = new IPEndPoint(IPAddress.Any, portNum);
                    socket.Bind(ep);
                    socket.Listen(100);

                    //SimpleServe(socket);

                    Task.Run(() => serveFunc(socket, processor));
                }
                catch (Exception)
                {
                    socket.Close();
                    throw;
                }
            }
Example #6
0
        static void ChannelParallelServe(Socket socket, RequestProcessor processor)
        {
            var ch = Channel.CreateBounded <(Socket conn, int connId)>(5000);

            var tasks = Enumerable.Repeat(new Func <Task>(() => Task.Run(async() =>
            {
                Console.WriteLine($"thread {Thread.CurrentThread.ManagedThreadId} initialized!");
                while (true)
                {
                    (Socket conn, int connId) = await ch.Reader.ReadAsync();
                    AsyncProcess(conn, connId, processor);
                }
            })), threadNumber).Select(f => f()).ToArray();
            int cnt = 0;

            while (true)
            {
                var conn = socket.Accept();
                ch.Writer.WriteAsync((conn, cnt++));
            }
        }
Example #7
0
        static void SimpleServe(Socket socket, RequestProcessor processor)
        {
            while (true)
            {
                var conn = socket.Accept();

                try
                {
                    var buf = new byte[1024];
                    conn.Receive(buf, 0, 1024, SocketFlags.None);
                    var response = Process(buf, 0, processor).Result;
                    conn.Send(response.Header);
                    conn.Send(response.Body);
                }
                catch (Exception)
                {
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Example #8
0
        static Task <(byte[] Header, byte[] Body)> Process(IEnumerable <byte> buf, int connId, RequestProcessor processor)
        {
            var request = GenerateRequest(buf, connId);

            return(processor.GenerateResponse(request));
        }