RobWarning
Posts: 6
Joined: Fri May 15, 2015 8:47 am

threading question

Wed Oct 07, 2015 5:28 pm

Hi,
I try to modify the blinky webserver app a little bit and put everything in one single Universal Windows app. So without the need of this inter - App communication service.
First I just like to show the incoming GET’s and the outgoing responces on my UI so I made a Universal Windows app.
Made a UI with 2 texboxes and a new Class file for the webserver with I call WebServerTask.

Code: Select all

using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Foundation;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;

namespace TuinWebApp
{
    public sealed class WebServerTask : IBackgroundTask
    {
        private BackgroundTaskDeferral serviceDeferal;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            taskInstance.Canceled += TaskInstance_Canceled;
            serviceDeferal = taskInstance.GetDeferral();
            InitializeServer();
        }

        private void InitializeServer()
        {
            HttpServer server = new HttpServer(8000);
            IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                (workItem) =>
                {
                    server.StartServer();
                });
        }

        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // this should stay empty.
        }
    }

    

    public sealed class HttpServer : IDisposable
    {
        private const uint BufferSize = 8192;
        private int Port = 8000;
        private readonly StreamSocketListener listener;

        public HttpServer(int serverPort)
        {
            listener = new StreamSocketListener();
            Port = serverPort;
            listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
        }

        public void StartServer()
        {
#pragma warning disable CS4014
            listener.BindServiceNameAsync(Port.ToString());
#pragma warning restore CS4014
        }

        public void Dispose()
        {
            listener.Dispose();
        }

        private async void ProcessRequestAsync(StreamSocket socket)
        {
            StringBuilder request = new StringBuilder();
            using (IInputStream input = socket.InputStream)
            {
                byte[] data = new byte[BufferSize];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = BufferSize;
                while (dataRead == BufferSize)
                {
                    await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            using (IOutputStream output = socket.OutputStream)
            {
                string requestMethod = request.ToString().Split('\n')[0];
                string[] requestParts = requestMethod.Split(' ');

                if (requestParts[0] == "GET")
                {
                    await WriteResponseAsync(requestParts[1], output);
                }

            }

        }

        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            //How to sync with the UI threat to display the request string?
        }
    }

       
}

I have now 2 questions related to threading.
1. How do I start the Webserver from within the Mainpage codebehind?
2 How can I display the Get and response strings from the server threat in the Mainpage UI threat?

thanks

Rob

Return to “Beginners”

Who is online

Users browsing this forum: Idahowalker and 47 guests