2015-06-15 29 views
0
public void RecievingClients(object obj) 
    { 
     //TcpListener tp = (TcpListener)obj; 
     while (true) 
     { 
      Socket s; 
      s = TcpLogin.AcceptSocket(); 
      s.ToString(); 
      NetworkStream ns = new NetworkStream(s); 
      StreamReader sr = new StreamReader(ns); 
      StreamWriter sw = new StreamWriter(ns); 
      string _LPInfo; 
      _LPInfo = sr.ReadLine(); 
      if (_LPInfo.Substring(0, 12) == "&*@[email protected]*&") 
      { 
       bool flag; 
       string _LP = _LPInfo.Substring(12); 
       string[] _LPSep; 
       _LPSep =_LP.Split('$'); 
       flag = _DBObj.Login(_LPSep[0],_LPSep[1]); 
       if (flag == true) 
       { 
        string ip = LocalIPAddress(); 
        sw.WriteLine("&@*IP*@&"+ip+":6090&" + _LPSep[0]); 
        sw.Flush(); 
       } 
       else 
       { 
        sw.WriteLine("Login Failed"); 
        sw.Flush(); 
       } 
      } 
      else if (_LPInfo.Substring(0, 12) == "&*@[email protected]*&") 
      { 
       bool flag; 
       string _LP = _LPInfo.Substring(12); 
       string[] _LPSep; 
       _LPSep = _LP.Split('$'); 
       string _SignUpQuery = "INSERT INTO SIGNUP_TABLE (USERNAME,PSWRD) Values('"+_LPSep[0]+ "','" +_LPSep[1] +"');"; 
       flag = _DBObj.QueryHandler(_SignUpQuery); 
       if (flag == true) 
       { 
        sw.WriteLine("SignUp Successsfully"); 
        sw.Flush(); 
       } 
       else 
       { 
        sw.WriteLine("SignUp Failed"); 
        sw.Flush(); 
       } 
      } 

這是我的大學項目。這是一個simole聊天信使,當我運行這個所有的代碼工作,但我得到了一個例外,如果條件是使用。 如果(_LPInfo.Substring(0,12)==「& @隆吉@ & 」) 這裏itcome 「 類型 'System.ArgumentOutOfRangeException' 的未處理的異常出現在mscorlib.dll發生異常我的c#項目中的參數範圍

其他信息:索引和長度必須指向字符串內的位置。「

+0

什麼_LPInfo'當異常的'值被拋出?我猜不是12個字符。 –

+0

'LPInfo'少於12個字符,所以'_LPInfo.Substring(0,12)'拋出一個異常。切換到'if(_LPInfo.Length> = 12 && _LPInfo.Substring(0,12)==「&@ Loginn @&」)'。 –

回答

1

問題在這裏。

_LPInfo.Substring(0, 12) 

12是子串的長度。現在發生的事情是,字符串的長度小於12,這意味着當使用子字符串時,字符串的長度超出了字符串的長度。

使用子字符串時,應確保字符串的長度比您正在檢查的字符串的數量更多。

if (_LPInfo.Length > 9 && _LPInfo.Substring(0, 10) == "&@[email protected]&") 
{ 
    // Do stuff here 
} 

此外請確保計算字符數。 「& @隆吉@ &」是僅10個字符不12.

0

String.Substring不開始於所述第一參數和具有第二參數的長度。如果_LPInfo爲空或超過12個字符小,你將有一個問題存在......無論是使用過載

if (_LPInfo != null && _LPInfo.Substring(0) == "&*@[email protected]*&") 
    {} 

或檢查長度第一

if (_LPInfo != null && _LPInfo.Length >= 12 && _LPInfo.Substring(0, 12) == "&*@[email protected]*&") 
    {} 
+0

我得到另一個異常,當使用這個:( – JOHN

+0

,你有什麼例外嗎?) –

+0

if(_Response.StartsWith(「&@ * IP * @&」)) 這裏我得到了空的異常 – JOHN