c# - 在字符位置上将字符串拆分为 2 个字符串
问题描述
我目前正在开发用于存储和搜索用户 ID(例如 542351)和位置(例如“在库中”)的客户端和服务器
这是我目前用来分隔接收到的客户端参数(用户 ID“位置”)的代码。
static void doRequest (NetworkStream socketStream)
{
string Protocol = "whois";
Dictionary<string, string> userLocationData = new Dictionary<string, string>();
try
{
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
//sw.WriteLine(args[0]);
//sw.Flush();
//Console.WriteLine(sr.ReadToEnd());
String Line = sr.ReadLine().Trim();
Console.WriteLine("Request Received: " + Line);
string[] sections = Line.Split(new char[] { ' ' }, 2);
string username = sections[0];
string location = sections[1];
string result;
if (location == null)
{
if (userLocationData.ContainsKey(username))
{
Console.WriteLine("Requested user location found."); //Server side only
userLocationData.TryGetValue(username, out result);
sw.WriteLine(result);
sw.Flush();
}
else
{
Console.WriteLine("Requested user location NOT found."); //Server side only
sw.WriteLine("ERROR: no entries found");
sw.Flush();
}
}
else
{
userLocationData.Add(sections[0], sections[1]);
if (userLocationData.ContainsKey(username))
{
Console.WriteLine("User location has been updated.");
sw.WriteLine("OK");
sw.Flush();
}
else
{
Console.WriteLine("Error, could not add user to database.");
}
}
}
catch
{
Console.WriteLine("Something went wrong");
}
}
基本上,我的服务器可以在发送 2 个参数时进行处理——因为它使用Line.Split(new char[] {' '}, 2);
问题是当用户只从客户端发送 1 个参数时,例如只发送用户 ID(6 位数字),服务器没有捕捉到它并抛出捕捉错误。
我认为这是因为当服务器仅接收用户 ID 1 参数时,它无法将字符串拆分为 2,因为没有空格或任何东西来填充第二个 section[1] 字符串。
本质上,如果它不仅仅是用户 ID,我只需要能够读取字符串并将其分成 2 个字符串。
例如 55432 “在库中” - 需要 2 个字符串
例如 55432 - 只会是 1 个字符串。
解决方案
推荐阅读
- reactjs - Mercure & API platform: auto-publish data
- python - 如何使用 atlassian rest api 在日期范围之间获取 Jira 问题数据
- php - 如果我将队列驱动程序设置为在 laravel 中同步,是否需要运行主管?
- ruby-on-rails - 在rails中不活动后会话超时之前的回调?
- java - Hibernate JPA 2 元模型生成器 - 错误“x_ 无法解析为变量”
- javascript - 将图像剪辑和缩放到画布而不会丢失质量
- docker - 本地 MQTT mosquitto 实例连接 ECONNREFUSED 127.0.0.1:1883
- javascript - 在一个输入中添加来自三个不同选择(其中两个有条件连接)的值
- performance - 当出现太多零窗口更新数据包时,是否是 TCP 连接的性能问题?
- recursion - 为什么这个时间复杂度是 O(total*n)?