这个问题在这里已有答案:
我的目标是通过服务器从其他客户端获取消息并处理该消息。服务器和其他客户端是visual basic,如果我尝试在两个vb客户端之间进行通信,一切都很好,但我需要c#中的客户端用于我的Unityproject。我的问题是控制台上仍然有空消息,所以我认为if()不正确。以下是本准则的相关部分:
try
{
theStream = mySocket.GetStream();
Byte[] inStream = new Byte[mySocket.SendBufferSize];
theStream.Read(inStream, 0, inStream.Length);
serverMsg += Encoding.ASCII.GetString(inStream);
serverMsg = serverMsg.Trim();
//if ((serverMsg == null || serverMsg == "")) doesn't work
//if (String.IsNullOrWhiteSpace(serverMsg)) doesn't work
//if (String.IsNullOrEmpty(serverMsg) || serverMsg.Length <1) doesn't work
INOWS = false;
INOWS = IsNullOrWhiteSpace(serverMsg);
if (INOWS)
{
// do nothing
}
else
{
Debug.Log("[SERVER] -> " + serverMsg);
}
}
catch (Exception e)
{
Debug.Log("[Fehler]" + e);
}
} while (socketReady == true);
public static bool IsNullOrWhiteSpace(string value)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
感谢您的提示,我尝试使用IsNullOrWhiteSpace,但这给了我一个错误"'string' does not contain a definition for IsNullOrWhiteSpace"
所以我使用this IsNullOrWhitespace但我仍然在控制台至少有一个空字符串为每个korrekt字符串。 console view你还有其他的提示吗?
if (String.IsNullOrWhitespace(serverMsg))
{
// do nothing
}
IsNullOrWhitespace()
检查null
,空白(“”)和空(“”)
尝试修剪字符串:如果字符串中包含任何空格字符,它仍将无法通过IsNullOrEmpty()测试。
在这种情况下(特别是用户或Web服务输入),我通常使用类似的东西
if ((s ?? "").Trim() != "")
{
// do whatever processing you need to do here...
...
)