C# 在c中的TcpListener中未处理NullReferenceException#
我正在尝试将C# 在c中的TcpListener中未处理NullReferenceException#,c#,asp.net,tcp,tcplistener,C#,Asp.net,Tcp,Tcplistener,我正在尝试将TcpListener连接到本地主机,以获得ip地址127.0.0.1和端口号8081 但我有个错误 NullReferenceException未处理 对象引用未设置为对象的实例 这是我的密码 public class Listener { private TcpListener tcpListener; private Thread listenThread; Int32 port = 8081; IPAddress localAddr = IP
TcpListener
连接到本地主机,以获得ip地址127.0.0.1和端口号8081
但我有个错误
NullReferenceException未处理对象引用未设置为对象的实例 这是我的密码
public class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
Byte[] bytes = new Byte[256];
public void ListenForClients()
{
//getting error at this line..
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
public void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
// System.Windows.MessageBox.Show("socket");
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
// System.Windows.MessageBox.Show("disc");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
String textdata = encoder.GetString(message, 0, bytesRead);
System.IO.File.AppendAllText(@"D:\ipdata.txt", textdata);
//mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
我在下面的代码行得到错误
this.tcpListener.Start();
您的TcpListener为空。您需要对它调用new并创建它的实际实例
private TcpListener tcpListener;
应该是
private TcpListener tcpListener = new TcpListener();
您只声明了
tcpListener
private TcpListener tcpListener;
它没有任何价值。它是空的
在使用它之前,必须先定义它
试一试
您不会在任何地方创建
tcpListener
的新实例。。尝试添加类似于tcpListener=newtcplistener(..)
创建实例时出错
private TcpListener tcpListener = new TcpListener();