Click here to Skip to main content
15,898,937 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi ,
there is problem :
im writing this code in form close event
C#
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    client.Shutdown(SocketShutdown.Both);//error :Object reference not sent to an instance of an object 
    client.Close();
}


when both programs (send and recieve program )are connected , there is no problem
but when i open server program and , close it before connect it to client program , this error shown , what i most to do to remove it ?
ok client program :
C#
private void Form1_Load(object sender, EventArgs e)
{
    IPAddress host = IPAddress.Parse("192.168.0.100");
    hostep = new IPEndPoint(host, 8001);
    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        sock.Connect(hostep);
        timer1.Enabled = true;
    }
    catch (Exception a)
    {
        label1.Text = a.Message;
    }
}

this is block that accept socket from server .
Posted
Updated 30-Mar-10 5:19am
v3

Unless there are related errors in code not shown, you could easily solve it like this:

C#
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (client!=null) {
        client.Shutdown(SocketShutdown.Both);// no NullRefExc
        client.Close();
    }
}


:)
 
Share this answer
 
Since the error is "Object reference not set to an instance of an object" the most likely culprit is that "client" is null. Since we can't see where you load this, I would check that.
 
Share this answer
 
You are using a variable called sock in your Load handler, but one called client in your FormClosing handler. Are these two code snippets from the same program?

If you don't set client to a Socket instance, then it will be null and cause the exception you are seeing.

Nick
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900