代码之家  ›  专栏  ›  技术社区  ›  Aleksa Ristic

Socket.EndReceive工作流

  •  1
  • Aleksa Ristic  · 技术社区  · 7 年前

    在…上 microsoft site 您可以找到以下代码: ReadCallback(IAsyncResult)

    static void ReadCallback(IAsyncResult ar)
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;
    
        int read = handler.EndReceive(ar);
    
        if(read > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
        }
        else
        {
            if(state.sb.Length > 1)
            {
                string content = state.sb.ToString();
    
                Console.WriteLine($"Read {content.Length} bytes from socket. \nData: {content}");
            }
            handler.Close();
        }
    }
    

    我不清楚的是这一点 if/else 陈述我们为什么要这样做 BeginReceive 再说一遍,如果我们已经读了什么?

    我们为什么不这样做呢

    static void ReadCallback(IAsyncResult ar)
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;
    
        int read = handler.EndReceive(ar);
    
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
    
        if(state.sb.Length > 1)
        {
            string content = state.sb.ToString();
    
            Console.WriteLine($"Read {content.Length} bytes from socket. \nData: {content}");
        }
        handler.Close();
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Louis Ingenthron    7 年前

    基本上,因为部分消息是一件事。

    请记住:即使您请求100个字节,EndReceive也会给您 高达 那么多字节。它不一定要等到它们都有了。

    推荐文章