I send some bytes on a specific port and listen on the same port :
udpBroadcast = new System.Net.Sockets.UdpClient(2333); // local binding
udpBroad开发者_C百科cast.Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true);
udpBroadcast.Connect("255.255.255.255", 2333);
udpBroadcast.Send(sendBytes, sendBytes.Length);
udpBroadcast.Close();
udpResponse = new System.Net.Sockets.UdpClient(2333); // local binding
udpResponse.Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true);
BeginAsyncReceive();
The problem is that I need to re-broadcast (for the other end sends me updates) but then I have an ObjectDisposedException
on udpBroadcast.
I understand Close()
disposed it but then I found no way to have it Opened.
Trying to recreate (new) udpBroadcast did not help.
Thanks
John
You may need to flush the data as well as sending it before closing and trying to re-open.This has caused me issues in the past before.
Eventually i used this pattern :
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
var endPoint = new IPEndPoint(ip, port);
socket.Bind(endPoint);
using (var client = new UdpClient() {Client = socket})
{
var destinationIP = IPAddress.Broadcast;
client.Connect(destinationIP, port);
client.Send(bytes, bytes.Length);
}
}
which i found at http://snipplr.com/view/28192/bind-a-socket-including-udpclient-and-tcpclient-to-a-local-network-interface-card-nic/ It works
精彩评论