Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows phone 7 无法在Windows phone中接收Udp_Windows Phone 7_Windows Phone 8_Windows Phone - Fatal编程技术网

Windows phone 7 无法在Windows phone中接收Udp

Windows phone 7 无法在Windows phone中接收Udp,windows-phone-7,windows-phone-8,windows-phone,Windows Phone 7,Windows Phone 8,Windows Phone,我试图将udp数据包从wp7模拟器发送到我的服务器(同一台pc上的java服务器),并得到一些响应。我使用了MSDN中SocketClient类的代码: 在以下情况下,它完全可以正常工作: 每次我创建Socketclient类的实例并调用send()和receive()方法时 使用send()发送数据包后,我可以通过调用receive()几个来接收多个数据包 但问题是- 我创建了Socketclient类的实例,调用send()和receive()方法,然后再次调用send()和receive(

我试图将udp数据包从wp7模拟器发送到我的服务器(同一台pc上的java服务器),并得到一些响应。我使用了MSDN中SocketClient类的代码:

在以下情况下,它完全可以正常工作:

  • 每次我创建Socketclient类的实例并调用send()和receive()方法时
  • 使用send()发送数据包后,我可以通过调用receive()几个来接收多个数据包
  • 但问题是-

  • 我创建了Socketclient类的实例,调用send()和receive()方法,然后再次调用send()和receive()(来自Socketclient类的同一个对象)。在这种情况下,它可以在bt无法接收时第二次发送数据包(给出响应“操作超时”) 如果我创建一个Socketclient类的新对象,以便再次发送和接收,它可以工作,但我必须在项目中始终使用单个套接字。我如何解决这个问题? 这是密码-

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    namespace UdpClient
    {
        class SocketClient
        {
            // Cached Socket object that will be used by each call for the lifetime of this class
            Socket _socket = null;
            // Signaling object used to notify when an asynchronous operation is completed
            static ManualResetEvent _clientDone = new ManualResetEvent(false);
            // Define a timeout in milliseconds for each asynchronous call. If a response is not received within this
            // timeout period, the call is aborted.
            const int TIMEOUT_MILLISECONDS = 5000;
            // The maximum size of the data buffer to use with the asynchronous socket methods
            const int MAX_BUFFER_SIZE = 2048;
            /// <summary>
            /// SocketClient Constructor
            /// </summary>
            public SocketClient()
            {
                // The following creates a socket with the following properties:
                // AddressFamily.InterNetwork - the socket will use the IP version 4 addressing scheme to resolve an address
                // SocketType.Dgram - a socket that supports datagram (message) packets
                // PrototcolType.Udp - the User Datagram Protocol (UDP)
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            }
            /// <summary>
            /// Send the given data to the server using the established connection
            /// </summary>
            /// <param name="serverName">The name of the server</param>
            /// <param name="portNumber">The number of the port over which to send the data</param>
            /// <param name="data">The data to send to the server</param>
            /// <returns>The result of the Send request</returns>
            public string Send(string serverName, int portNumber, string data)
            {
                string response = "Operation Timeout";
                // We are re-using the _socket object that was initialized in the Connect method
                if (_socket != null)
                {
                    // Create SocketAsyncEventArgs context object
                    SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                    // Set properties on context object
                    socketEventArg.RemoteEndPoint = new DnsEndPoint(serverName, portNumber);
                    // Inline event handler for the Completed event.
                    // Note: This event handler was implemented inline in order to make this method self-contained.
                    socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                    {
                        response = e.SocketError.ToString();
                        // Unblock the UI thread
                        _clientDone.Set();
                    });
                    // Add the data to be sent into the buffer
                    byte[] payload = Encoding.UTF8.GetBytes(data);
                    socketEventArg.SetBuffer(payload, 0, payload.Length);
                    // Sets the state of the event to nonsignaled, causing threads to block
                    _clientDone.Reset();
                    // Make an asynchronous Send request over the socket
                    _socket.SendToAsync(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;
            }
    
    
    
    
            /// <summary>
            /// Receive data from the server
            /// </summary>
            /// <param name="portNumber">The port on which to receive data</param>
            /// <returns>The data received from the server</returns>
            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)
                    {
                        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();
                    });
                    // 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;
            }
    
            /// <summary>
            /// Closes the Socket connection and releases all associated resources
            /// </summary>
            public void Close()
            {
                if (_socket != null)
                {
                    _socket.Close();
                }
            }
    
        }
    }
    
    使用系统;
    使用System.Collections.Generic;
    使用System.Linq;
    使用系统文本;
    使用System.Net.Sockets;
    使用系统线程;
    Net系统;
    命名空间UdpClient
    {
    类SocketClient
    {
    //在该类的生存期内每次调用都将使用的缓存套接字对象
    套接字_Socket=null;
    //用于在异步操作完成时通知的信令对象
    静态手动复位事件_clientDone=新手动复位事件(假);
    //为每个异步调用定义一个超时(以毫秒为单位)。如果在此时间内未收到响应
    //超时期间,呼叫被中止。
    const int TIMEOUT_毫秒=5000;
    //用于异步套接字方法的数据缓冲区的最大大小
    const int MAX_BUFFER_SIZE=2048;
    /// 
    ///SocketClient构造函数
    /// 
    公共SocketClient()
    {
    //以下操作将创建具有以下属性的套接字:
    //AddressFamily.InterNetwork-套接字将使用IP版本4寻址方案解析地址
    //Dgram—支持数据报(消息)包的套接字
    //Udp-用户数据报协议(Udp)
    _套接字=新套接字(AddressFamily.InterNetwork、SocketType.Dgram、ProtocolType.Udp);
    }
    /// 
    ///使用已建立的连接将给定数据发送到服务器
    /// 
    ///服务器的名称
    ///要通过其发送数据的端口号
    ///要发送到服务器的数据
    ///发送请求的结果
    公共字符串发送(字符串服务器名、int端口号、字符串数据)
    {
    string response=“操作超时”;
    //我们正在重新使用在Connect方法中初始化的_socket对象
    if(_socket!=null)
    {
    //创建SocketAsyncEventArgs上下文对象
    SocketAsyncEventArgs socketEventArg=新的SocketAsyncEventArgs();
    //设置上下文对象的属性
    SocketEventTarget.RemoteEndPoint=新的DnsEndPoint(服务器名、端口号);
    //已完成事件的内联事件处理程序。
    //注意:此事件处理程序是内联实现的,目的是使此方法自包含。
    SocketEventTarget.Completed+=新事件处理程序(委托(对象s,SocketAsyncEventArgs e)
    {
    响应=e.SocketError.ToString();
    //取消阻止UI线程
    _clientDone.Set();
    });
    //将要发送的数据添加到缓冲区中
    byte[]有效负载=Encoding.UTF8.GetBytes(数据);
    SocketEventTarget.SetBuffer(有效载荷,0,有效载荷.长度);
    //将事件的状态设置为未签名,从而导致线程阻塞
    _clientDone.Reset();
    //通过套接字发出异步发送请求
    _socket.SendToAsync(socketEventArg);
    //阻止UI线程的最大超时时间为\u毫秒。
    //如果在此时间内没有回复,则继续
    _clientDone.WaitOne(超时\u毫秒);
    }
    其他的
    {
    response=“套接字未初始化”;
    }
    返回响应;
    }
    /// 
    ///从服务器接收数据
    /// 
    ///用于接收数据的端口
    ///从服务器接收的数据
    公共字符串接收(int端口号)
    {
    string response=“操作超时”;
    //我们正在通过已建立的套接字连接接收数据
    if(_socket!=null)
    {
    //创建SocketAsyncEventArgs上下文对象
    SocketAsyncEventArgs socketEventArg=新的SocketAsyncEventArgs();
    SocketEventTarget.RemoteEndPoint=新的IPEndPoint(IPAddress.Any,端口号);
    //设置缓冲区以接收数据
    SocketEventTarget.SetBuffer(新字节[最大缓冲区大小],0,最大缓冲区大小);
    //已完成事件的内联事件处理程序。
    //注意:这个偶数处理程序是内联实现的,目的是使这个方法自包含。
    SocketEventTarget.Completed+=新事件处理程序(委托(对象s,SocketAsyncEventArgs e)
    {
    如果(e.SocketError==SocketError.Success)
    {
    //从缓冲区中检索数据
    response=Encoding.UTF8.GetString(e.Buffer,e.Offset,e.bytesttransfered);
    response=response.Trim('\0');
    }
    其他的
    {
    响应=e.SocketError.ToString();
    }