Reptic
Reptic

Reputation: 175

C# A request to send or receive data was disallowed because the socket is not connected

So am trying to send a packet but am keep getting this error

Any help would be awesome!

Thanks a lot!

Error Message: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

Code:

    private void button1_Click(object sender, EventArgs e)
    {
        byte[] packetData = Encoding.ASCII.GetBytes(textBox1.Text);

        const string ip = "127.0.0.1";
        const int port = 5588;


        var ep = new IPEndPoint(IPAddress.Parse(ip), port);


        var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.SendTo(packetData, ep);
    }
}

}

Upvotes: 2

Views: 26338

Answers (3)

user703016
user703016

Reputation: 37945

var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

This creates a socket that will use TCP (which is a stream protocol). If you want to call Socket.SendTo on a connection oriented socket, you have to connect it first, through a call to Socket.Connect.

If you are intending to send datagrams only, it is a better choice to use UDP instead, which does not require connecting at all.

var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)

Upvotes: 2

JoelC
JoelC

Reputation: 3754

I think what you are looking for is calling client.Connect before calling client.SendTo. You'll also want to call client.Connected after you call connect to ensure you are connected.

This help page has an example of using the socket object: http://msdn.microsoft.com/en-us/library/2b86d684%28v=vs.110%29.aspx.

    // Connect to the host using its IPEndPoint.
    s.Connect(hostEndPoint);

    if (!s.Connected)
    {
      // Connection failed, try next IPaddress.
      strRetPage = "Unable to connect to host";
      s = null;
      continue;
    }

Upvotes: -2

Allan Elder
Allan Elder

Reputation: 4094

private void button1_Click(object sender, EventArgs e)
{
    byte[] packetData = Encoding.ASCII.GetBytes(textBox1.Text);

    const string ip = "75.126.77.26";
    const int port = 5588;


    var ep = new IPEndPoint(IPAddress.Parse(ip), port);


    var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    client.Connect(ep);
    client.SendTo(packetData, ep);
}

for clarity, added this line:

    client.Connect(ep);

Upvotes: 1

Related Questions