2015-10-09 164 views
-2

在下面的代碼中,我得到空引用異常,我不明白爲什麼我得到這個。請幫我解決它。空引用異常問題

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.Net.Sockets; 
using System.Threading; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace TCPListener 
{ 
    public partial class Form1 : Form 
    { 
     // Declare our worker thread 
     private Thread workerThread = null; 

     public Form1() 
     { 
      InitializeComponent(); 
      // Initialise and start worker thread 
      this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData)); 
      this.workerThread.Start(); 
     } 



     public void timer1_Tick(object sender, EventArgs e) 
     { 

     } 

     public TcpListener server = null; 
     public Int32 port = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO"].ToString()); 
     public IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["IP"].ToString()); 

     public void OpenSocket() 
     { 
      try 
      { 
       // TcpListener server = new TcpListener(port); 
       server = new TcpListener(localAddr, port); 

       // Start listening for client requests. 
       server.Start(); 
      } 
      catch (SocketException e) 
      { 
       Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message); 
      } 
      finally 
      { 
       Common.CommonControls.writeToLogFile("INICIO DE ESCUCHA EN " + DateTime.Now); 
      } 

     } 

     private void ReceiveTcpData() 
     { 

      //Instancio los objetos 
      Entities.Program oPosiciones = new Entities.Program(); 
      DataAccess.Program oPosicionesDA = new DataAccess.Program(); 

      try 
      { 
       // Buffer for reading data 
       Byte[] bytes = new Byte[256]; 
       String data = null; 

       // Enter the listening loop. 

       // Perform a blocking call to accept requests. 
       // You could also user server.AcceptSocket() here. 
       //TcpClient client = server.AcceptTcpClient(); 

       TcpClient cliente = new TcpClient(); 
       try 
       { 
        cliente = server.AcceptTcpClient(); 
       } 
       catch (Exception e) { MessageBox.Show(e.ToString()); } 

       data = null; 

       // Get a stream object for reading and writing 
       NetworkStream stream = cliente.GetStream(); 

       int i; 

       // Loop to receive all the data sent by the client. 
       while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) 
       { 
        // Translate data bytes to a ASCII string. 
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 

        // Process the data sent by the client. 
        data = data.ToUpper(); 

        if (data.Substring(0, 2) == "##") 
        { 
         //SalidaMonitor("Paquete recibido: LOGON REQUEST del equipo"); 
         cliente.Close(); 
         this.workerThread.Interrupt(); 
         return; 
        } 

        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); 

        //Show data on monitor 
        SalidaMonitor("Paquete recibido " + DateTime.Now + ": " + data); 

        //Declare entities 
        oPosiciones.Paquete = data; 

        //Database action 
        oPosicionesDA.InsertarPosiciones(oPosiciones); 

        // Send back a response. 
        //stream.Write(msg, 0, msg.Length); 

        //SalidaMonitor("Paquete enviado: " + msg); 
       } 

       // Shutdown and end connection 
       cliente.Close(); 

      } 

      catch (SocketException e) 
      { 
       Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message); 
      } 
      catch (SqlException x) 
      { 
       Common.CommonControls.writeToLogFile("SQL ERROR: " + x.Message); 
      } 
      catch (Exception y) 
      { 
       Common.CommonControls.writeToLogFile("ERROR: " + y.Message); 
      } 
      finally 
      { 
       oPosiciones = null; 
       oPosicionesDA = null; 
       this.workerThread.Interrupt(); 

      } 
     } 

     private void SalidaMonitor(string data) 
     { 
      lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.Items.Add(data.ToString()); })); 
      lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.SelectedIndex = lstMensajes.Items.Count - 1; lstMensajes.SelectedIndex = -1; })); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      OpenSocket(); 
     } 
     private void Form1_Close(object sender, FormClosingEventArgs e) 
     { 
      server.Stop(); 
     } 

    } 
} 

在上面的代碼,我在cliente = server.AcceptTcpClient得到錯誤();。我不明白爲什麼會發生。如果您需要任何信息,請告訴我。謝謝

回答

0

那麼,如果它在那一行,這是因爲server未初始化。

+0

如何初始化它?如果我們使它爲空,我們將得到如何初始化它的同樣的錯誤。我在我的日誌文件中得到下面的錯誤。 10/9/2015 4:56:10 AM:錯誤:對象引用未設置爲對象的實例。 –

+0

你在'OpenSocket()'中初​​始化它。您只需確保在嘗試接受客戶端之前調用它。 –

+0

我不明白你的觀點,可以請你給我那塊代碼,我必須修改。大蝦 –

1

的問題

正在創建和啓動新線程的形式的構造函數

。 和這個線程將調用ReceiveTcpData方法,哪個用戶server變量(在這一點上這個變量還沒有初始化)爲什麼?

,因爲server變量在中初始化,它調用OpenSocket方法初始化server變量。最重要的部分是方法被稱爲AFTER表單的構造函數。 換句話說,線程在初始化之前使用server變量。

解決方案

使用下面的構造函數,並刪除事件處理程序

public Form1() 
{ 
    InitializeComponent(); 

    // add this line. 
    OpenSocket(); 

    // Initialise and start worker thread 
    this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData)); 
    this.workerThread.Start(); 
} 

更新

對於誰喜歡在 這裏做的一切的人是另一種解決方案

public Form1() 
{ 
    InitializeComponent(); 
} 

private void Form1_Load(object sender, EventArgs e) 
{ 
    // add this line. 
    OpenSocket(); 

    // Initialise and start worker thread 
    this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData)); 
    this.workerThread.Start(); 
} 
+0

我寧願在Form_Load中做所有事情(當然除了InitializeComponent())。 – JeffRSon

+0

@JeffRSon我爲你更新了我的答案。 –