【发布时间】:2019-01-28 12:44:57
【问题描述】:
我有一个 switch 语句,它使用从 char[] 转换而来的字符串,该字符串通过数据流从服务器发送到客户端。代码是客户端的。
即使服务器和默认错误代码始终完全匹配大小写,也会始终命中默认大小写。
SERVER SIDE
private void SendToClient(string message, TcpAccount account)
{
try
{
byte[] buffMessage = Encoding.ASCII.GetBytes(message);
account.TcpClient.GetStream().WriteAsync(buffMessage, 0, buffMessage.Length);
log.AppendText(string.Format("Message {0} sent to account {1}", message, account.ID));
log.AppendText(Environment.NewLine);
}
catch
{
log.AppendText(string.Format("Message {0} sent to account {1}", message, account.ID));
log.AppendText(Environment.NewLine);
}
}
CLIENT SIDE
public async void ReadDataAsync(TcpClient client)
{
try
{
StreamReader clientStreamReader = new StreamReader(client.GetStream());
char[] buff = new char[64];
int readByteCount = 0;
while (true)
{
readByteCount = await clientStreamReader.ReadAsync(buff, 0, buff.Length);
if (readByteCount <= 0)
{
Console.WriteLine("Disconnected from server.");
client.Close();
break;
}
string code = new string(buff);
ProcessServerCode(code);
Array.Clear(buff, 0, buff.Length);
}
}
catch
{
}
}
public void ProcessServerCode(string code)
{
switch (code)
{
case "regcom":
MessageBox.Show("Registration Complete");
break;
case "logcom":
MessageBox.Show("Login Complete");
break;
case "badpass":
MessageBox.Show("Invalid Password");
break;
case "badaccount":
MessageBox.Show("Invalid Account");
break;
default:
MessageBox.Show("Unknown Code: " + code);
break;
}
}
我无法从默认代码中删除它。
另外,由于我是客户端/服务器和套接字编程的新手,我刚刚意识到服务器发送一个字节[],但客户端接收一个字符[]。那里有冲突吗?有什么特别的原因(因为我使用的是在线培训课程中的那些特定代码)?
【问题讨论】:
-
您是否尝试调试客户端代码接收到的内容?如果你总是点击默认值,那么你的输入不是你所期望的
-
您可以尝试修剪收到的字符串,更新此行
string code = new string(buff).Trim();。我认为这可能是一个原因,因为您等待接收 64 个字节,但在您的示例中接收到的字符串较少 -
旁注:从不使用
async void。即使您不关心结果,您也应该始终使用async Task。这里的一个关键原因是async关心同步上下文,并且存在许多 主动阻止async void的同步上下文 - 特别是但不限于 ASP.NET 同步上下文.这意味着您可以发现代码在一个系统中运行良好,而当您更改版本/平台/等时,由于同步上下文差异(一个允许async void,一个不允许)。所以:永远不要使用async void -
@MarcGravell 谢谢!我已经进行了更改,并且一定会在将来避免异步无效。
-
另一个旁注:你实际上不是
await-ingWriteAsync- 你真的应该等待
标签: c# arrays string tcp switch-statement