简体   繁体   English

服务器中的字典和字符串拆分

[英]dictionary and string split in server

Hi I am having problem with my dictionary initialization. 嗨,我的字典初始化有问题。 I have to declare a dictionary and populated with the (userName) and (location) which I am reciving from the client. 我必须声明一个字典,并用我从客户端接收的(userName)和(location)填充。 when it finds the userName it should send back the location if not it shouls send back"no entries found" and if the location is it updated then it should say "OK". 当找到用户名时,应将其发送回该位置,否则应发送“未找到条目”,如果位置已更新,则应说“确定”。 Right now i am getting an out of bounds error can someone help me fix it. 现在,我遇到了界外错误,有人可以帮助我修复它。 thank you. 谢谢。

protected static Dictionary<string, string> dict = new Dictionary<string, string>();

static void doRequest(NetworkStream socketStream)
{
    try
    {
        StreamWriter sw = new StreamWriter(socketStream);
        StreamReader sr = new StreamReader(socketStream);

        String line = sr.ReadLine();   
        Console.WriteLine("Respond recived " + line);

        String[] sections = line.Split(new char[] { ' ' }, 2);

        dict.TryGetValue(sections[0],out sections[1]);

        if(sections[0].Length>1)
        {
            sw.WriteLine(sections[1]);
            sw.Flush();
        }
        else
        {
            sw.WriteLine("no entries found");
            sw.Flush();
        }
        if(sections[1].Length>2)
        {
            sw.WriteLine("OK");
            sw.Flush();
        }

    catch (Exception e)
    {
        Console.WriteLine(e);

    }

}

Potentially, these 2 lines are the problem: 这两条线可能是问题所在:

String[] sections = line.Split(new char[] { ' ' }, 2);
dict.TryGetValue(sections[0],out sections[1]);

If line.Split returns 1 string (say the line doesn't have any spaces), then sections[1] (the second string in the array) will not exist and you get an IndexOutOfRangeException. 如果line.Split返回1个字符串(例如该行没有空格),则sections [1](数组中的第二个字符串)将不存在,并且您将获得IndexOutOfRangeException。

I would recommend using a separate variable for the TryGet 我建议为TryGet使用一个单独的变量

dict.TryGetValue(sections[0],var out foundValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM