Daaksin
Daaksin

Reputation: 894

This operation is not allowed on Non-connected sockets

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();
        }
    }

Upvotes: 2

Views: 14062

Answers (1)

Roland Bär
Roland Bär

Reputation: 1730

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.

Upvotes: 2

Related Questions