4

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

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

添加了我的主要课程以帮助回答问题

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

3 回答 3

3

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

于 2013-08-26T21:58:27.177 回答
2

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

于 2013-02-18T17:24:07.713 回答
2

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

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

解决方案

尝试 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();
于 2016-05-18T14:17:46.960 回答