windows 7.x移动设备中的UDP接收
本文关键字:UDP 接收 移动 windows | 更新日期: 2023-09-27 17:58:06
我在使用Windows Mobile时遇到问题。
我正在编写一个代码,用于从windows服务器应用程序(由我创建)接收UDP数据,该应用程序广播数据,但当windows应用程序执行时,我遇到了一个可怕的问题:
提供了无效参数
当套接字CCD_ 1功能工作时。
有人能帮我吗?
---这是代码
public string Receive(int portNumber)
{
string response = "Operation Timeout";
// We are receiving over an established socket connection
registerSocket();
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();
_socket.ReceiveFromAsync(socketEventArg);
});
// 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);** // here the issue arises An //invalid argument was supplied
// 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;
}
我找到了解决方案。
要接收Udp多播,您应该在接收之前调用_socket.Bind(IPEndpoint)
,并使用_socket.ReceiveAsync()
而不是_socket.ReceiveFromAsync()
。此外,socketEventArg.RemoteEndpoint
应为空。
这个代码对我有效:
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(new byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
args.Completed += args_Completed;
_socket.Bind(new IPEndPoint(IPAddress.Any, **your port**));
_socket.ReceiveAsync(args);