可能重复:
NullReferenceException on instanciated object?
What is a NullReferenceException in .NET?
我已经在C#中构建了一个TCP客户端,当客户端无法连接时我得到了以下内容。 我继续使用以下代码获取NullReference异常,我无法想象如何捕获它或停止它...任何帮助将不胜感激。
它发生在“int a = sReponseData.Length”
{
string sMesg = "LogOn Ext:" + txtdevice.Text;
SendMessage(sMesg);
int a = sResponseData.Length;
//Geting the Script out of the message.
if (a > 10)
{
string stemp = sResponseData;
string[] sSplit = stemp.Split(new Char[] { ';'});
foreach (string s in sSplit)
{
if ((s.Trim() != "Tag") & (s.Trim() != "StopStart"))
sScript = s;
}
}
}
}
这是sMesg
{
InitializeComponent();
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
//Int32 port = 13000;
TcpClient client = new TcpClient("127.0.0.1", 32111);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(sMsg);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//MessageBox.Show("Sent: {0}" + sMsg);
// Receive the TcpServer.response.
// String to store the response ASCII representation.
sResponseData = String.Empty;
if (stream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (stream.DataAvailable);
// Print out the received message to the console.
sResponseData = myCompleteMessage.ToString();
//MessageBox.Show(sResponseData);
}
else
{
sResponseData = ("3");
MessageBox.Show("TagIt Server is unavalible at this moment.");
}
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
WriteLog("ArgumentNullException: {0}" + e);
MessageBox.Show("TagIt Server is unavalible at this moment.");
}
catch (SocketException e)
{
WriteLog("SocketException: {0}" + e);
MessageBox.Show("TagIt Server is unavalible at this moment.");
}
}
答案 0 :(得分:0)
您可以检查响应数据是否有值:
类似的东西:
int a;
try
{
if(sResponseData==null || sResponseData=="" )
{
MessageBox.Show("ResponseData is NULL or Empty"); //Shows Error
}
else
{
//SresponseData has value
string sMesg = "LogOn Ext:" + txtdevice.Text;
SendMessage(sMesg);
a= Convert.ToInt32(sResponseData).Length;
//Geting the Script out of the message.
if (a > 10)
{
string stemp = sResponseData;
string[] sSplit = stemp.Split(new Char[] { ';'});
foreach (string s in sSplit)
{
if ((s.Trim() != "Tag") & (s.Trim() != "StopStart"))
sScript = s;
}
}
}
}
catch (Execption ex)
{
MessageBox.Show(ex.Message); //Shows Error
}
答案 1 :(得分:0)
在检查sResponseData的长度之前,请确保检查sResponseData是否为空。