根据字符位置将字符串分成2个字符串

时间:2019-03-17 23:26:47

标签: c# string server client readline

我目前正在开发用于存储和搜索用户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);

将其分为2个字符串

问题是,当用户仅从客户端发送1个参数时,例如只是用户ID(6位数字),服务器不会捕获它,而是抛出捕获错误。

我认为这是因为当服务器仅接收用户ID(1个参数)时,由于没有空间或任何内容可填充第二部分[1]字符串,因此无法将字符串拆分为2。

本质上,如果不仅仅是用户ID,我只需要能够读取字符串并将其分成2个字符串即可。

例如55432“在库中”-必须为2个字符串

例如55432-只能是1个字符串。

0 个答案:

没有答案
相关问题