-2

In the below code, I am getting null reference exception I didn't understand why I am getting that. Please help me to solve it.

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();
        }

    }
}

In the above code, I am getting error at cliente = server.AcceptTcpClient();. I don't understand why it's happening. If you need any information, let me know. Thanks

Christian.K
  • 42,600
  • 9
  • 89
  • 127
HF nava
  • 15
  • 4

2 Answers2

1

The Problem

in the constructor of the form you are creating and starting new Thread. and this thread will call the ReceiveTcpData method, which user the server variable (and at this point this variable was not initialized yet) WHY??

because the server variable is initialized in the Form_Load which call the OpenSocket method to initalize the server variable. The most important part is The Form_Load method is called AFTER the constructor of the form. In other words, the Thread is using the server variable before you initialize it.

The Solution

use the following constructor, and remove the Form_Load event handler

public Form1()
{
     InitializeComponent();

     // add this line.
     OpenSocket();

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

Update

For the person who prefer to do everything in the Form_Load here is another solution

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();
}
Hakan Fıstık
  • 11,376
  • 8
  • 74
  • 105
0

Well, if it is in that line, it is because server is not initialized.

Alvaro Gutierrez Perez
  • 3,061
  • 1
  • 14
  • 24
  • How to initialize it ? if we make it null we will get the same error how to initialize it. I am getting the below error in my log file. 10/9/2015 4:56:10 AM: ERROR: Object reference not set to an instance of an object. – HF nava Oct 09 '15 at 07:17
  • You initialize it in `OpenSocket()`. All you need to do is to ensure you call it before trying to accept clients. – Alvaro Gutierrez Perez Oct 09 '15 at 07:41
  • I dont understand your point, can u please give me that piece of code where i have to modify.THanks – HF nava Oct 09 '15 at 11:19
  • 1
    @ÁlvaroGutiérrez this should not be answer, this should be a comment on the question. – Hakan Fıstık Oct 11 '15 at 08:23