0

Ok, so I have a little chat server that receives messages from a little chat client.

This client has a little "send" button:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:TextBox id="ServerDataArea" TextMode="multiline" Columns="50" Rows="15" runat="server" Enabled="false" />
        <br />
        <asp:TextBox ID="Message" runat="server" ></asp:TextBox>
        <asp:Button ID="SendMessage" runat="server" OnClick="SendMessage_Click" Text="Send" />
    </ContentTemplate>
</asp:UpdatePanel>

This is what little the "send" button want to do:

public partial class _Default : System.Web.UI.Page
{
    private MessageHandlerThread mHandler;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            mHandler = new MessageHandlerThread(ServerDataArea);
        }
    }

    /// <summary>
    /// send message
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SendMessage_Click(object sender, EventArgs e)
    {
        Debug.WriteLine("send clicked");

        if (Message.Text != "")
        {
            mHandler.StoreMessage(Message.Text);
        }
    }
}

When I run the website first time my little server tells me "client connected" and its all good like that but when I press the "send" button it yells at me for reasons such as:

Object reference not set to an instance of an object.

meaning that mHandler = null and that's a big problem for me, it's not at all what I want. I want to use the mHandler that was created the first time I loaded the page. If I remove "if (!IsPostBack)" from "Page_Load" it will make a new connection every time I press "send" and that's also not what I want because I want to use the same TcpClient connection to receive data as well as send it in my client thread.

1
  • 1
    The class instance is completely different between ASP.NET and WinForms. On ASP.NET, the class instance is made newly by every user request. So you should save the instance in the session like @Mark saying. Commented Feb 24, 2014 at 10:56

1 Answer 1

2

Save the mHandler in the session state and it will persist across postbacks (assuming the code is running on one web server).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.