简体   繁体   English

如何创建用于处理异步数据传输的包装器?

[英]How can I create a wrapper for handling Async data transfer?

I'm trying to create a async wrapper for my project so that I can tidy up my code and not write the same code over and over again for the objects I'm sending back and forth with the server. 我正在尝试为我的项目创建一个异步包装程序,这样我就可以整理代码,而不必一遍又一遍地为与服务器来回发送的对象编写相同的代码。

I'm planning to use protobuf, but for the sake of this thread I've changed the object to string. 我打算使用protobuf,但是为了这个线程,我将对象更改为字符串。

My mambo-jambo code: 我的曼波-詹博代码:

    public class AsyncWrapper
    {
        public void Run(Uri url, string requestString, string responseString, WebHeaderCollection headerCollection)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Headers = headerCollection;
            request.BeginGetRequestStream((s) => 
            {
                var req = (HttpWebRequest)s.AsyncState;
                var str = req.EndGetRequestStream(s);

                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                Byte[] bytes = encoding.GetBytes(responseString);

                str.Write(bytes, 0, bytes.Length);
                str.Close();

                req.BeginGetResponse((k) => 
                {
                    var req2 = (HttpWebRequest)k.AsyncState;
                    var resp = (HttpWebResponse)req2.EndGetResponse(k);

                    byte[] bytes2 = ReadFully(resp.GetResponseStream());

                    string res = System.Text.Encoding.Unicode.GetString(bytes2);

                }, req);

            }, null);
        }

        private static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }

What I'm trying to do is create one function that wraps the whole procedure of the "two-step" way of communication with the server: first the initial request, then the response. 我正在尝试做的是创建一个函数,该函数包装与服务器通信的“两步”通信方式的整个过程:首先是初始请求,然后是响应。

Am I on the right path? 我在正确的道路上吗? I'm missing a crucial part; 我缺少关键的部分; eventhandling. 事件处理。 The plan was to rais an event at string res = System... to let the application know that the job is done. 计划是在string res = System...上引发一个事件,以使应用程序知道作业已完成。

If I'm understanding correctly, you want to turn a long synchronous operation in an asynchronous operation. 如果我理解正确,则希望在异步操作中进行长时间的同步操作。 You can do that with threading: 您可以使用线程来做到这一点:

public class AsyncWrapper
{
    public event Action<string> RunCompleted;

    public void Run(Uri url, string requestString, string responseString, WebHeaderCollection headerCollection)
    {
        Thread thread = new Thread(new ParameterizedThreadStart(RunThread));

        thread.start(new [] { url, requestString, responseString, headerCollection });
    }

    public void RunThread(object Obj)
    {
        object[] ObjArray = (object[])Obj;

        Uri url = (Uri)ObjArray[0];
        string requestString = (string)ObjArray[1];
        string responseString = (string)ObjArray[2];
        WebHeaderCollection headerCollection = (WebHeaderCollection)ObjArray[3];

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Headers = headerCollection;
        request.BeginGetRequestStream((s) => 
        {
            var req = (HttpWebRequest)s.AsyncState;
            var str = req.EndGetRequestStream(s);

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            Byte[] bytes = encoding.GetBytes(responseString);

            str.Write(bytes, 0, bytes.Length);
            str.Close();

            req.BeginGetResponse((k) => 
            {
                var req2 = (HttpWebRequest)k.AsyncState;
                var resp = (HttpWebResponse)req2.EndGetResponse(k);

                byte[] bytes2 = ReadFully(resp.GetResponseStream());

                string res = System.Text.Encoding.Unicode.GetString(bytes2);

            }, req);

        }, null);

        if (RunComleted != null)
        {
            RunCompleted(res);
        }
    }

    private static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM