不允许发送或接收数据的请求,因为套接字未连接C#

时间:2014-10-24 11:17:44

标签: c# connect server

我正在尝试向机器发送用户名和密码身份验证响应,但我收到了以下错误

不允许发送或接收数据的请求,因为套接字未连接(使用sendto调用在数据报套接字上发送时)没有提供地址

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

1 个答案:

答案 0 :(得分:4)

您尝试在侦听传入连接的套接字上发送数据:

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

您应该通过accepted发送它:

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