简体   繁体   中英

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

}

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM