当前上下文中不存在名称“sb”

问题描述

我刚刚开始使用 C# 并尝试使用套接字服务器从客户端应用程序接收一些数据。

这是从客户端应用程序接收的字符串:

Value0_Value1_Value2

接收到的数据像这样继续附加到先前接收到的字符串

Value0_Value1_Value2 Value0_Value1_Value2Value0_Value1_Value2 Value0_Value1_Value2Value0_Value1_Value2Value0_Value1_Value2 Value0_Value1_Value2Value0_Value1_Value2Value0_Value1_Value2Value0_Value1_Value2

所以我试图清除 StringBuilder,一旦从客户端收到数据,但我收到一个 错误 说:

名称“sb”在当前上下文中不存在

这是从客户端接收数据的代码

public static void ReadCallback(IAsyncResult ar)
{
 
    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);
    if (bytesRead > 0)
    {

        string proce0,proce1,proce2,proce3,proce4,proce5 = String.Empty;
        state.sb.Append(Encoding.ASCII.GetString(
        state.buffer,bytesRead));
         
        content = state.sb.ToString();
        Console.WriteLine(content);

        string[] Splitdata1 = content.Split('_');
        int splitelements = Splitdata1.Length;
        Console.WriteLine(splitelements);
        if (splitelements == 3)
        {
            proce0 = Splitdata1[0];
            proce1 = Splitdata1[1];
            proce2 = Splitdata1[2];
            Console.WriteLine("Values:\n" + proce0 + "\n" + proce1 + "\n" + proce2 + "\n" + "\n" + "\n");
            sb.Clear();
        }
        if (content.IndexOf("END5") > -1)
        {
            Console.WriteLine(content);
            Send(handler,content);
            sb.Clear();
        }
        else
        {
            handler.BeginReceive(state.buffer,StateObject.BufferSize,new AsyncCallback(ReadCallback),state);

        }
    }
}

包含字符串生成器的 StateObject 类:

public class StateObject

{
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
    public Socket workSocket = null;
}

清除 StringBuilder 以便字符串不会附加到先前接收的字符串的正确方法是什么? 或者是否有其他方法可以摆脱附加的字符串?

解决方法

sb 变量未在整个 ReadCallback() 方法中定义。它可作为 StateObject 类的属性使用。您需要清除 sb 类中的 StateObject,例如

state.sb.Clear();

你的代码看起来像,

public static void ReadCallback(IAsyncResult ar)
{
    ...
    if (bytesRead > 0)
    {
        //****You have already done it over here****
        state.sb.Append(Encoding.ASCII.GetString(
        state.buffer,bytesRead));
        if (splitelements == 3)
        {  
            ...
            state.sb.Clear();  //Change sb.Clear() to state.sb.Clear()
        }
        if (content.IndexOf("END5") > -1)
        { 
            ...
            state.sb.Clear();  //Change sb.Clear() to state.sb.Clear()
        }
        ...
    }
}