【发布时间】:2012-02-12 23:37:43
【问题描述】:
可能重复:
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;
}
}
}
}
这里是短信
{
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.");
}
}
【问题讨论】:
-
在代码的哪一行你得到了异常?阅读整个异常消息。
-
该行中唯一可以为空的是
sResponseData。所以我猜第二个函数永远不会被调用,但如果没有更多信息就不可能知道。启动调试器并验证 sResponseData 实际上是否为 null 您收到错误的位置,您的第二个函数以查看它是否被调用,如果没有,则无论哪个函数调用它以查看它被跳过的原因,等等。跨度>