This operation is not allowed on Non-connected sockets

12,686

When the StreamWriter is disposed (at the end of the using block) the used Stream gets also closed.

After the Send() Method you try to use the closed stream resulting in the described exception.

Share:
12,686
Daaksin
Author by

Daaksin

Hey, I'm Daaksin. Programming is the best way to both relax and spin your head in circles for hours on end. Progamming sometimes causes lack of sleep due to frustration over bugs and such, but its well worth it. Here are the languages I do: C# .NET (Usually 2.0) C++ (I lose the most sleep over this one) Python Java I favour writing network applications, advanced chat programs, basic 2D topdown LAN games etc. Oh yeah, and I'm Australian. Chuck anotha shrimp on tha barbie, ay! No I don't ride Kangaroos to work, but that'd be awesome!

Updated on June 04, 2022

Comments

  • Daaksin
    Daaksin almost 2 years

    Consider the following:

        public void Connect()
        {
            clientObject = new TcpClient();
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 90);
            centralForm.writeLog("Connecting to desired server", System.Drawing.Color.Gray, true);
            clientObject.Connect(ipEnd);
            if ((debug) && (clientObject.Connected)) { Debug.Print("Connected"); }
    
            Send("0");
            clientObject.GetStream().BeginRead(new byte[] { 0 }, 0, 0, Read, null);
        }
    

    I get the error stated above on the last line in this snippet of code. What have I done wrong? I have called Connect()... I've stared at this for ages and I genuinely have no idea what I have done wrong.

    Send Code:

        public void Send(string data)
        {
            using (StreamWriter w = new StreamWriter(clientObject.GetStream()))
            {
                w.WriteLine(data);
                w.Flush();
            }
        }
    
  • Daaksin
    Daaksin over 10 years
    Thank you. I understand now.
  • The Little Cousin
    The Little Cousin almost 7 years
    Hello, How did you fix that issue?