我試圖連接TcpListener
到本地主機的IP地址127.0.0.1和端口號8081 但我得到一個錯誤的NullReferenceException中的TcpListener是未處理的在C#
的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'的'一個新實例..嘗試添加類似'的TCPListener =新的TcpListener(..)' –