2013-11-25 58 views
-1

我試圖連接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(); 
+1

你不隨地創建tcpListener'的'一個新實例..嘗試添加類似'的TCPListener =新的TcpListener(..)' –

回答

2

你的TcpListener爲空。你需要調用new並創建一個實例。

private TcpListener tcpListener; 

大概應該是

private TcpListener tcpListener = new TcpListener(); 
+0

創建實例給錯誤 – Adi

2

你只宣佈tcpListener

private TcpListener tcpListener; 

它沒有任何價值。它是空的。

在使用它之前,您必須先定義它。

嘗試

private TcpListener tcpListener = new TcpListener(); 
相關問題