C# 发送或接收数据的请求被禁止,因为套接字未连接 - 发送数据时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14940553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:29:41  来源:igfitidea点击:

A request to send or receive data was disallowed because the socket is not connected - when sending data

c#socketsudp

提问by Andrew Zak

I am trying to send data back to the client when the server receives "debug". ATM the following provides this error:

当服务器收到“调试”时,我试图将数据发送回客户端。ATM 以下提供此错误:

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.

由于套接字未连接并且(使用 sendto 调用在数据报套接字上发送时)未提供地址,因此不允许发送或接收数据的请求。

Added my main class to help answer questions

添加了我的主类来帮助回答问题

    static Socket newSocket;
    static byte[] data;
    static EndPoint tmpRemote;
    static IPEndPoint sender, endpoint;
    static int recv;
    static void Main(string[] args)
    {
        data = new byte[1024];

        endpoint = new IPEndPoint(IPAddress.Any, 3000);

        newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        newSocket.Bind(endpoint);



        sender = new IPEndPoint(IPAddress.Any, 904);
        tmpRemote = (EndPoint)sender;

        newSocket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref tmpRemote, new AsyncCallback(OperatorCallBack), data);

        Console.Read();
    }



    private static void OperatorCallBack(IAsyncResult ar)
    {
        log("[" + DateTime.Now + "][New Connection] " + tmpRemote.ToString() + "");
        try
        {
            int size = newSocket.EndReceiveFrom(ar, ref tmpRemote);
            if (size > 0)
            {
                data = (byte[])ar.AsyncState;
                string[] dataCommand = Encoding.ASCII.GetString(data, 0, size).Split(' ');
                if (dataCommand[0] == "debug")
                {
                    newSocket.Send(Encoding.ASCII.GetBytes("HA IT WORKED :)"));
                    log("Sent debug");
                }
                else
                {
                    log("Invalid Command");
                }
            }
            data = new byte[1024];
            newSocket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref tmpRemote, new AsyncCallback(OperatorCallBack), data);
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp.Message);
        }
    }

回答by user207421

The error message is quite clear. You are calling send() on an unconnected socket and without providing a target address. Where are you sending to? UDP doesn't know.

错误信息非常清楚。您在未连接的套接字上调用 send() 并且没有提供目标地址。你要寄到哪里?UDP 不知道。

回答by Peter Beeby

I had similar issues when trying to connect to sockets over a slow connection. I resolved it by making sure the newSocket.Connected property was true before any Send/Receive calls.

我在尝试通过慢速连接连接到套接字时遇到了类似的问题。我通过在任何发送/接收调用之前确保 newSocket.Connected 属性为真来解决它。

回答by Abzkn

As connection(socket.connect()) is not needed when you send data via ProtocolType.Udp that error may occur when you dont suggest the address wher UDP Message should forward

由于当您通过 ProtocolType.Udp 发送数据时不需要 connection(socket.connect()),当您不建议 UDP 消息应转发的地址时,可能会发生错误

IN YOUR CASEhere the address is not provided for udp Send()

在您的情况下,这里没有为 udp Send() 提供地址

SOLUTION

解决方案

Try SendTo() instead

试试 SendTo()

Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soc.EnableBroadcast = true;
IPEndPoint ipend = new IPEndPoint(IPAddress.Broadcast, 58717);
EndPoint endp = (EndPoint)ipend;
byte[] bytes = new byte[1024];

bytes = Encoding.ASCII.GetBytes(str);

soc.SendTo(bytes,ipend);

soc.Close();