首页新闻招聘找找看知识库

各位大佬门我想问一下,对于异步,如何可以在Receive方法中得到ReceiveCallBack()中 int bytesRead = client.EndReceive(ar); bytesRead值?

0
悬赏园豆:5 [已解决问题]
 private static void Receive(Socket client) {
        try {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ReceiveCallback( IAsyncResult ar ) {
        try {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0) {
                // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                    new AsyncCallback(ReceiveCallback), state);
            } else {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1) {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }
(时光)光阴飞逝的主页 (时光)光阴飞逝 | 初学一级 | 园豆:197
提问于:2017-11-17 17:00
< >
分享
最佳答案
0

ar.asyncResult

 

你要的东西在这个变量里

收获园豆:5
猝不及防 | 小虾三级 |园豆:690 | 2017-11-17 17:31

你好,非常感谢你的回答。但你说得这个变量还是存在于ReceiveCallBack(IAsyncResult ar)里的吧,如果不是的话我又该如何在Receive(Socket Client)来获取呢?

(时光)光阴飞逝 | 园豆:197 (初学一级) | 2017-11-20 08:50

@(时光)光阴飞逝: 

if(ar.isfinished)
{
bytesRead=(int)ar.asyncResult;
}

好像是这样,原来好像用过一次

猝不及防 | 园豆:690 (小虾三级) | 2017-11-20 17:13

@猝不及防: 这个虽然有,但不是我想要得这种,但还是非常感谢!我就结帖了,豆子还是给你,谢谢你的帮忙

(时光)光阴飞逝 | 园豆:197 (初学一级) | 2017-11-24 11:50
   您需要登录以后才能回答,未注册用户请先注册