【问题标题】:UDP Socket receive fails in wp7wp7中的UDP Socket接收失败
【发布时间】:2012-01-26 02:27:07
【问题描述】:

我是 WP7 和 Socket 编程的新手。我已经浏览了 msdn 示例代码http://msdn.microsoft.com/en-us/library/hh202864(v=VS.92).aspx#Y4537 并进行了使用测试。发送工作正常,但无法接收,这是我用于接收 udp 数据包数据的代码。

在此我的断点总是失败@if (e.SocketError == SocketError.Success)

    public string Receive(int portNumber)
    {
        string response = "Operation Timeout";

        // We are receiving over an established socket connection
        if (_socket != null)
        {
            // Create SocketAsyncEventArgs context object
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);

            // Setup the buffer to receive the data
            socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

            // Inline event handler for the Completed event.
            // Note: This even handler was implemented inline in order to make this method self-contained.
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                try
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        // Retrieve the data from the buffer
                        response = Encoding.UTF8.GetString(e.Buffer, e.Offset,e.BytesTransferred);
                        response = response.Trim('\0');
                    }
                    else
                    {
                        response = e.SocketError.ToString();
                    }
                    _clientDone.Set();
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }

            });

            // Sets the state of the event to nonsignaled, causing threads to block
            _clientDone.Reset();

            // Make an asynchronous Receive request over the socket
            _socket.ReceiveFromAsync(socketEventArg);


            // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
            // If no response comes back within this time then proceed
            _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
        }
        else
        {
            response = "Socket is not initialized";
        }

        return response;
    }

【问题讨论】:

    标签: sockets windows-phone-7


    【解决方案1】:

    您是否尝试过在 WP7/Silverlight 中使用特定的 UDP 支持?根据您的方案和要求使用UdpSingleSourceMulticastClientUdpAnySourceMulticastClient。这是一篇关于 Silverlight 中 UDP 的介绍文章 @Working with Multicast

    【讨论】:

    • :您能提供任何 UDP 接收的工作示例吗?
    • 没有。根据您要完成的工作,有许多 Silverlight 4 博客文章解释了使用我刚刚提到的 2 个类实现 UDP 的更精细点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多