我正在创建一个程序来监听传入的字符串,它工作…我目前编写的代码是有效的问题是如果他们发送字符串我的程序会抛出参数超出范围异常
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace Stringlistener
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(my port number);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10000000000025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
}
String:
<?xml version="1.0" encoding="utf-8"?>
<faf>
<hah>
<gr>00.00</gr>
<yy>000000000</yy>
</hah>
<ee>
<gr>00.00</gr>
<yy>000000000</yy>
</ee>
</faf>
任何想法?问题是从我这边来的,如果是这样,我该如何解决?
我希望了解这一点,以防止同样的问题在将来再次发生
thanks in advance
第32行的IndexOf
调用如果没有找到搜索字符串则返回-1。假设来自客户端的数据不包含"$"
字符串。Substring(int, int)需要第一个参数中的起始索引和第二个参数中的长度。如果在提供的字符串中没有找到,IndexOf
将返回-1。
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
在字符串中查找"$"。如果dataFromClient
不包含"$",则IndexOf
返回-1,这使得Substring
看起来像这样:
dataFromClient.Substring(0, -1)
文档(上面的链接)指出,当startIdnex + length指示不在本实例中的位置或startIndex或length小于零时,将抛出ArgumentOutOfRangeException
。
长度必须大于0,-1显然不是。