为什么BeginReceive()不会返回多次读取? [英] Why does BeginReceive() not return for more than one read?

查看:45
本文介绍了为什么BeginReceive()不会返回多次读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我从 Main()调用了 Receive(),后者又调用了 Async BeginReceive(),并在后台线程中完成数据的接收.

In the code below, I make a call from Main() to Receive(), which in turn calls the Async BeginReceive(), and completes receiving the data in a background thread.

问题:对于第一次阅读,BeginReceive成功,并附加了StringBuilder.但是,再次调用时,将永远不会达到 if(bytesread> 0)条件,因此,我也不会对接收到的数据采取任何措施.我希望BeginReceive处理多个读取,并且(我认为这与线程相关),我希望 Main()函数始终侦听来自客户端的新COMMANDS(而不是新的连接,我想保持相同的套接字).这有可能吗?

The Problem: For the first read, BeginReceive is succesful and appends the StringBuilder. However, when called again, the if(bytesread>0) condition is never reached and thus I never act on the data received. I want BeginReceive to deal with more than one read, and (i think this is related with the threading) I would like for the Main() function to be always listening for new COMMANDS from the client (not new connections, I'd like to keep the same Socket). Is this even possible?

尝试解决方法:我添加了ManualResetEvent,以尝试在另一个线程进行异步读取之前阻止 Main()函数退出.

Attempts At Solution: I added the ManualResetEvent in an attempt to stop the Main() function from exiting prior to the Async reading going on in another thread.

Main()中的相关代码:

Relevant Code in Main():

        Receive(server); //await instructions from the client
        done.WaitOne(); //This is a ManualResetEvent.
        Console.ReadLine();

方法定义:

        public static void Receive(Socket server)
    {
        try
        {
            SocketArgs sockargs = new SocketArgs();
            sockargs.handler = server;


             server.BeginReceive(sockargs.buffer, 0, sockargs.buffersize, 0, new AsyncCallback(ReceiveCallBack), sockargs);

        }
        catch
        {

        }
    }
    public static void ReceiveCallBack(IAsyncResult ia)
    {
        try
        {
            SocketArgs sockargs = (SocketArgs)ia.AsyncState;
            Socket server = sockargs.handler;
            int BytesRead = server.EndReceive(ia);
            if (BytesRead > 0)
            {
                //Continue reading data.
                sockargs.sb.Append(Encoding.ASCII.GetString(sockargs.buffer, 0, BytesRead));
                MessageBox.Show(sockargs.sb.ToString());
                server.BeginReceive(sockargs.buffer, 0, sockargs.buffersize, 0, new AsyncCallback(ReceiveCallBack), sockargs);
            }
            else
            { //Do stuff with sb.ToString()



                done.Set();
            }
        }
        catch(Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

推荐答案

重置事件,以便 WaitOne 再次阻止.根据评论,该事件被错误地设置为设置状态,导致Main退出.

Reset the event so that WaitOne blocks again. As per the comments the event is erroneously left in a set state causing Main to exit.

这篇关于为什么BeginReceive()不会返回多次读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆