简体   繁体   中英

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

I am trying to send username and password authentication response to machine but I am getting following error

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

static void Main(string[] args)
{
    Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    sck.Bind(new IPEndPoint(IPAddress.Parse("192.168.5.40"), 10022));

    sck.Listen(1);

    Socket accepted = sck.Accept();
    byte[] buffer = Encoding.Default.GetBytes("Test post");
    accepted.Send(buffer, 0, buffer.Length, 0);

    buffer = new byte[255];

    int rec = accepted.Receive(buffer, 0, buffer.Length, 0);
    Array.Resize(ref buffer, rec);
    Console.WriteLine("Recieved: {0}", Encoding.Default.GetString(buffer,24,buffer.Length-24));
    Console.WriteLine("Recieved: {0}", BitConverter.ToString(buffer, 0, 24));

    string hexValues = "00-00-00-01-f8-a0-3d-48-0b-6d-00-00-3d-0a-bf-09-00-00-00-57-00-10-00-00-00";

    byte[] hex = StringToByteArray(hexValues);

    sck.Send(hex, 0, hex.Length, 0);
    sck.Close();
    accepted.Close();
    Console.Read();
}

You attempt to send data on the socket listening for incoming connections:

sck.Send(hex, 0, hex.Length, 0);

you should send it through accepted instead:

accepted.Send(hex, 0, hex.Length, 0);

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