1

I'm trying to create a small udp server and client. I'm coding the log off functionality now, but for some reason I get a ObjectDisposedException.

Data msgToSend = new Data ();
msgToSend.cmdCommand = Command.Logout;
msgToSend.strName = strName;
msgToSend.strMessage = null;

byte[] b = msgToSend.ToByte ();
clientSocket.SendTo(b, 0, b.Length, SocketFlags.None, epServer);
clientSocket.Close();

The server receives the message. And then does what it is supposed to, but when I reach the clientSocket.Close() I get the exception.

Bildsoe
  • 1,310
  • 6
  • 31
  • 44
  • What's the "the" in "the does what it is supposed to"? – bzlm Aug 29 '11 at 10:58
  • I get an ObjectDisposeException - no other details. Someone provided an answer telling me that it is because i did'nt use socket.open, because it is udp. But the answer dissapeared. – Bildsoe Aug 29 '11 at 10:59
  • What does it mean "no other details"? Catch the exception and see which object triggered it. From what it seems now, there should be no error. – Eli Iser Aug 29 '11 at 11:08
  • In a related note, I'm fairy certain you should wrap your sockets in a **using** statement and never bother closing them. – Gleno Aug 29 '11 at 11:14
  • When catching the exception I output the source object, but I just get System as the answer. I get the exception multiple times on each run, so I'm thinking that somehow additional calls are being made after i close it. – Bildsoe Aug 29 '11 at 11:46

1 Answers1

1

the error must be somewhere else because it's ok to call Close after SendTo, here a snippet from MSDN: http://msdn.microsoft.com/en-us/library/beez6ewa.aspx

 public static void SendTo4()
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
        IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);

        Socket s = new Socket(endPoint.Address.AddressFamily,
            SocketType.Dgram,
            ProtocolType.Udp);

        byte[] msg = Encoding.ASCII.GetBytes("This is a test");
        Console.WriteLine("Sending data.");
        // This call blocks. 
        s.SendTo(msg, 0, msg.Length, SocketFlags.None, endPoint);
        s.Close();
    }
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • Strange, because the sendTo works, but the Close throws the exception. Is this different from version to version of .Net? – Bildsoe Aug 29 '11 at 11:09