NullRefExc on netStream & tcpClient

54 views Asked by At

I am making a website in ASP.NET 4.0. Currently I am coding the aspx.cs file. Only on the first time connecting to my page, I want to establish a connection to a TcpClient and open a NetStream. Then on every postback I want to send data to the TcpClient. What happens is that I get a NullReferenceException on my netStream variable when I try to check whether I can write to it.

Code:

public partial class Domos : System.Web.UI.Page
{
    TcpClient tcpClient;
    NetworkStream netStream;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {

        }
        else
        {
            tcpClient = new TcpClient("localhost", 11000);
            netStream = tcpClient.GetStream();
        }
    }

    private void InteractHouse(string command)
    {
        //TcpClient tcpClient = new TcpClient("localhost", 11000);
        //NetworkStream netStream = tcpClient.GetStream();

        if(netStream.CanWrite)
        {
            Byte[] sendBytes = Encoding.UTF8.GetBytes(command + " \n");
            netStream.Write(sendBytes, 0, sendBytes.Length);
        }
        else
        {
            tcpClient.Close();
            netStream.Close();
        }

        if(netStream.CanRead)
        {
            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

            netStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);

            string returndata = Encoding.UTF8.GetString(bytes);
        }
        else
        {
            tcpClient.Close();
            netStream.Close();
            return;
        }

        netStream.Close();
        tcpClient.Close();
    }

    protected void btn_raamLinksDicht_Click(object sender, EventArgs e)
    {
        InteractHouse("window 0 close");
    }
}

During debugging, I noticed that before I get to my method InteractHouse, first the debugger goes to my MasterPage.Master.Cs and runs the page_load method which does nothing at the time of writing. Once I get to InteractHouse method, the debugger doesn't have any references to my variables tcpClient and netStream. However I want the connection to uniquely load on only my page Domos (House).

Am I looking at it from the wrong point of view? I appreciate any help.

0

There are 0 answers