首页 > 解决方案 > 在字符位置上将字符串拆分为 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 个字符串。

标签: c#stringserverclientreadline

解决方案


推荐阅读