Question

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.

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top