public void inicializarMulticasting() {// 236.0.0.0 if (this.receptorAtribuido) { try { servidorMulticast.Close(); servidorMulticast.DropMulticastGroup(endMulticast); servidorMulticast.Dispose(); servidorMulticast = null; } catch (Exception ex) { servidorMulticast = null; Multicasting = null; } } servidorMulticast = new UdpClient(); servidorMulticast.DontFragment = true;//não quero que fragmente os pacotes //this.meuEnd = new IPEndPoint(IPAddress.Any, portaMulticast); this.meuEnd = new IPEndPoint(IP, portaMulticast); servidorMulticast.Client.Bind(meuEnd); servidorMulticast.EnableBroadcast = true; servidorMulticast.JoinMulticastGroup(endMulticast); this.receptorAtribuido = true; }
public void DisposeClose_OperationsThrow(bool close) { var udpClient = new UdpClient(); for (int i = 0; i < 2; i++) // verify double dispose doesn't throw { if (close) { udpClient.Close(); } else { udpClient.Dispose(); } } IPEndPoint remoteEP = null; Assert.Throws <ObjectDisposedException>(() => udpClient.BeginSend(new byte[1], 1, null, null)); Assert.Throws <ObjectDisposedException>(() => udpClient.EndSend(null)); Assert.Throws <ObjectDisposedException>(() => udpClient.BeginReceive(null, null)); Assert.Throws <ObjectDisposedException>(() => udpClient.EndReceive(null, ref remoteEP)); Assert.Throws <ObjectDisposedException>(() => udpClient.JoinMulticastGroup(IPAddress.Loopback)); Assert.Throws <ObjectDisposedException>(() => udpClient.JoinMulticastGroup(IPAddress.Loopback, IPAddress.Loopback)); Assert.Throws <ObjectDisposedException>(() => udpClient.JoinMulticastGroup(0, IPAddress.Loopback)); Assert.Throws <ObjectDisposedException>(() => udpClient.JoinMulticastGroup(IPAddress.Loopback, 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.DropMulticastGroup(IPAddress.Loopback)); Assert.Throws <ObjectDisposedException>(() => udpClient.DropMulticastGroup(IPAddress.Loopback, 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.Connect(null)); Assert.Throws <ObjectDisposedException>(() => udpClient.Connect(IPAddress.Loopback, 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.Connect("localhost", 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.Receive(ref remoteEP)); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(null, 0, remoteEP)); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(null, 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(null, 0, "localhost", 0)); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(new ReadOnlySpan <byte>(), remoteEP)); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(new ReadOnlySpan <byte>())); Assert.Throws <ObjectDisposedException>(() => udpClient.Send(new ReadOnlySpan <byte>(), "localhost", 0)); Assert.Throws <ObjectDisposedException>(() => { udpClient.SendAsync(null, 0, remoteEP); }); Assert.Throws <ObjectDisposedException>(() => { udpClient.SendAsync(null, 0); }); Assert.Throws <ObjectDisposedException>(() => { udpClient.SendAsync(null, 0, "localhost", 0); }); Assert.Throws <ObjectDisposedException>(() => udpClient.SendAsync(new ReadOnlyMemory <byte>(), remoteEP)); Assert.Throws <ObjectDisposedException>(() => udpClient.SendAsync(new ReadOnlyMemory <byte>())); Assert.Throws <ObjectDisposedException>(() => udpClient.SendAsync(new ReadOnlyMemory <byte>(), "localhost", 0)); Assert.Throws <ObjectDisposedException>(() => { udpClient.ReceiveAsync(); }); Assert.Throws <ObjectDisposedException>(() => udpClient.ReceiveAsync(default));
private void SignOutButtonClick(object sender, RoutedEventArgs e) { SignOutItemEnabled(); byte[] buffer = Encoding.UTF8.GetBytes($"{userNameTextBox.Text} leaves the chat"); _client.Send(buffer, buffer.Length, _ipEndPoint); _client.DropMulticastGroup(_ipAddress); _isConnect = false; _client.Close(); chatTextBox.Clear(); }
public async Task ReaderAsync() { using (var client = new UdpClient(Port)) { if (GroupAddress != null) { Logger.Debug($"JoinMulticastGroup = {GroupAddress}"); client.JoinMulticastGroup(IPAddress.Parse(GroupAddress)); } bool completed; do { Logger.Debug("Listening..."); UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer;; string received = Encoding.UTF8.GetString(datagram); Logger.Info($"Received (from {result.RemoteEndPoint.Address})-> {received}"); completed = (received.ToLower() == "stop"); } while (!completed); if (GroupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(GroupAddress)); } Logger.Info("Receiver closed"); } }
/// <summary> /// 接收器工作 /// </summary> /// <returns></returns> public async Task ReceiveAsync() { using (var client = new UdpClient(Port)) { if (GroupAddress != null) { Logger.Debug($"Join Multicast Group = {GroupAddress}"); client.JoinMulticastGroup(IPAddress.Parse(GroupAddress)); } Logger.Debug("Start Listening...Sending in [stop] to stop listening"); bool completed; do { UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer; MessageRecieved?.Invoke(this, new UdpReceivedEventArgs(datagram)); string received = Encoding.UTF8.GetString(datagram); Logger.Info($"Received (from {result.RemoteEndPoint.Address}) < {received}"); completed = (received.ToLower() == "stop"); } while (!completed); if (GroupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(GroupAddress)); } Logger.Warn("Listening stop command received."); Logger.Warn("Udp is stopping..."); } }
public void JoinDropMulticastGroup_InvalidArguments_Throws() { using (var udpClient = new UdpClient(AddressFamily.InterNetwork)) { Assert.Throws <ArgumentNullException>("multicastAddr", () => udpClient.JoinMulticastGroup(null)); Assert.Throws <ArgumentNullException>("multicastAddr", () => udpClient.JoinMulticastGroup(0, null)); Assert.Throws <ArgumentNullException>("multicastAddr", () => udpClient.JoinMulticastGroup(null, 0)); Assert.Throws <ArgumentException>("ifindex", () => udpClient.JoinMulticastGroup(-1, IPAddress.Any)); Assert.Throws <ArgumentOutOfRangeException>("timeToLive", () => udpClient.JoinMulticastGroup(IPAddress.Loopback, -1)); Assert.Throws <ArgumentNullException>("multicastAddr", () => udpClient.DropMulticastGroup(null)); Assert.Throws <ArgumentNullException>("multicastAddr", () => udpClient.DropMulticastGroup(null, 0)); Assert.Throws <ArgumentException>("multicastAddr", () => udpClient.DropMulticastGroup(IPAddress.IPv6Loopback)); Assert.Throws <ArgumentException>("ifindex", () => udpClient.DropMulticastGroup(IPAddress.Loopback, -1)); } }
// выход из чата private void ExitChat() { string message = "e \n"; message += LOCALPORT; byte[] data = Encoding.Unicode.GetBytes(message); client.Send(data, data.Length, HOST, REMOTEPORT); //отправка имени пользователя message = "o \n"; message += userName + "\r\n"; data = Encoding.Unicode.GetBytes(message); client.Send(data, data.Length, HOST, REMOTEPORT); message = "0 \n"; message += userName + " покидает чат"; data = Encoding.Unicode.GetBytes(message); client.Send(data, data.Length, HOST, REMOTEPORT); client.DropMulticastGroup(groupAddress); alive = false; client.Close(); SubmitionOfPortAndIP.IsEnabled = true; Exit_Button.IsEnabled = false; Send_Button.IsEnabled = false; UserMessage.IsEnabled = false; NicknameInput.IsReadOnly = false; InputPort.IsReadOnly = false; InputIP.IsReadOnly = false; }
/// <summary> /// 进行UDP协议数据的发送 /// </summary> /// <param name="endpoint"></param> /// <param name="broadcast"></param> /// <param name="groupAddress"></param> /// <param name="input"></param> /// <returns></returns> public async Task Sender(IPEndPoint endpoint, bool broadcast, string groupAddress, string input) { try { //进行地址的获取 string localhost = Dns.GetHostName(); //获取或设置系统。布尔值值,该值指定System.Net.Sockets接口.UdpClient可以发送或接收广播数据包。 using var client = new UdpClient { EnableBroadcast = broadcast }; //进行地址组的判断 if (groupAddress != null) { //加入多播组 client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); } //进行字符数组的获取 byte[] datagram = Encoding.UTF8.GetBytes(input); //发送数据 int sent = await client.SendAsync(datagram, datagram.Length, endpoint); //进行地址组的获取 if (groupAddress != null) { //推出多播组 client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } catch (SocketException ex) { throw ex; } }
/// <summary> /// UDP接受器 /// </summary> /// <param name="port">端口号</param> /// <param name="groupAddress">IP地址组</param> /// <param name="stopstr">停止符</param> /// <returns></returns> public async Task ReaderAsync(int port, string groupAddress, string stopstr) { //创建Udp客户端 using var client = new UdpClient(port); //获取端口组 if (groupAddress != null) { //解析IP client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); } bool completed = false; do { //进行UDP的接受 UdpReceiveResult result = await client.ReceiveAsync(); //从结果中获取字节数组 byte[] datagram = result.Buffer; //进行字符串装换 string received = Encoding.UTF8.GetString(datagram); if (received == stopstr) { completed = true; } } while (!completed); if (groupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } }
/// <summary> /// 在创建一个UdpClient实例,并将字符串转换为字节数组后,就使用SendAsync方法发送数据。 /// 请注意接收器不需要侦听,发送方也不需要连接。UDP是很简单的。 /// 然而,如果发送方把数据发送到未知的地方一一一无人接收数据,也不会得到任何错误消息 /// </summary> /// <param name="endpoint"></param> /// <param name="broadcast"></param> /// <param name="groupAddress"></param> private void SenderStart(IPEndPoint endpoint, bool broadcast, string groupAddress) { try { string locahost = Dns.GetHostName(); using (var client = new UdpClient()) { client.EnableBroadcast = broadcast; if (groupAddress != null) { client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); } bool completed = false; do { Console.WriteLine("请输入信息或者输入bye退出"); string input = Console.ReadLine(); Console.WriteLine(); completed = input == "bye"; byte[] datagram = Encoding.UTF8.GetBytes($"{input} from {locahost}"); } while (!completed); if (groupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } } catch (SocketException ex) { Console.WriteLine(ex.Message); } }
private void ReceiveProc() { try { while (userIsConnected) { IPEndPoint remoteEP = null; byte[] buffer = client.Receive(ref remoteEP); string messageReceive = Encoding.ASCII.GetString(buffer); if (messageReceive.Contains("disabled")) { Dispatcher.Invoke(() => namesUser.Remove(ListOnline(messageReceive))); userIsConnected = false; } else if (messageReceive.Contains("join")) { namesUser.Add(ListOnline(messageReceive)); } Dispatcher.Invoke(() => chat.AppendText($"{messageReceive}\n")); Dispatcher.Invoke(() => clients.ItemsSource = namesUser); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { client.DropMulticastGroup(IPAddress.Parse(ipAddres)); client.Close(); } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting /// unmanaged resources. /// </summary> /// <param name="disposing">Indicates whether this method was called from the /// <see cref="Dispose()"/> method</param> protected virtual void Dispose(bool disposing) { if (_cancellationTokenSource != null) { _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); } _listenTask?.Wait(TimeSpan.FromSeconds(5)); if (_receiveResultQueue != null) { _receiveResultQueue.Complete(); _receiveResultQueue.Completion.Wait(TimeSpan.FromSeconds(5)); } if (_broadcastClient != null) { _broadcastClient.DropMulticastGroup(_groupAddress); _broadcastClient.Close(); } if (_listenerClient != null) { _listenerClient.DropMulticastGroup(_groupAddress); _listenerClient.Close(); } }
} // Main public static void Terminate() { lock (typeof(Chat)) { m_Client.DropMulticastGroup(m_GroupAddress); } //lock } //Terminate()
private void LeaveGroup() { try { if (group != null) { SendMessage("Leaving Chat"); Application.DoEvents(); Thread.Sleep(500); stayAlive = false; Application.DoEvents(); receiveThread.Abort(); client.DropMulticastGroup(group); client.Close(); client = null; group = null; multiCastEP = null; this.Text = "Multicast Chat"; Thread.Sleep(500); } } catch (Exception e) { MessageBox.Show("An exception occurred when attempting to Leave Group: \n" + e.ToString(), "Leave Group Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Dispose(); } }
static void Main(string[] args) { //UdpClient 객체 생성 - 13000 포트 UdpClient rev = new UdpClient(13000); //IPAddess 객체 생성 - 가입할 멀티캐스트 주소를 저장할 객체 224.0.1.0 IPAddress multicast_ip = IPAddress.Parse("224.0.1.0"); //멀티캐스트 가입 //JoinMulticastGroup(IPAddress 객체) : IPAddress객체가 저장한 IP주소(멀티캐스트주소) //로 해당 UDP소켓이 가입하는 기능이 있는 메소드 rev.JoinMulticastGroup(multicast_ip); //IPEndPoint객체 생성 - 0,0 인자로 사용 IPEndPoint ip = new IPEndPoint(0, 0); BinaryFormatter formatter = new BinaryFormatter(); for (; ;) { //데이터 수신 - byte[] byte[] recv_data = rev.Receive(ref ip); //byte[]을 MemoryStream 에 객체생성시 인자값으로 사용 MemoryStream stream = new MemoryStream(recv_data); //MemoryStream에 커서위치를 데이터 맨앞으로 이동 stream.Seek(0, SeekOrigin.Begin); //BinaryFormatter로 Deserialize 메소드 호출로 string 변환 string str = (string)formatter.Deserialize(stream); //결과출력 Console.WriteLine("{0}/{1} : {2}", ip.Address.ToString(), ip.Port, str); stream.Close(); } //가입한 멀티캐스트 그룹을 탈퇴 rev.DropMulticastGroup(multicast_ip); //UdpClient 객체 연결 종료 rev.Close(); }
} // Worker_ProgressChanged void Worker_DoWork(object sender, DoWorkEventArgs e) { UdpClient client; IPEndPoint endPoint; StartTime = DateTime.Now; client = null; try { client = new UdpClient(MulticastPort); client.JoinMulticastGroup(MulticastIpAddress); statusLabelReceiving.Text = "Trying to connect..."; endPoint = null; while (!Worker.CancellationPending) { var data = client.Receive(ref endPoint); Worker.ReportProgress(0, data); } // while } finally { if (client != null) { client.DropMulticastGroup(MulticastIpAddress); client.Close(); } // if } // finally } // Worker_DoWork
private static async Task ReaderAsync(int port, string groupAddress) { using (var client = new UdpClient(port)) { IPAddress multicastAddr = null; if (groupAddress != null) { multicastAddr = IPAddress.Parse(groupAddress); client.JoinMulticastGroup(multicastAddr); WriteLine("Joining the multicast group {0}", multicastAddr); } var completed = false; do { WriteLine("Starting the receiver"); var result = await client.ReceiveAsync().ConfigureAwait(false); var datagram = result.Buffer; var received = Encoding.UTF8.GetString(datagram); WriteLine("Received {0}", received); if (received == "bye") { completed = true; } } while (!completed); WriteLine("Receiver closing"); if (groupAddress != null && multicastAddr != null) { client.DropMulticastGroup(multicastAddr); } } }
/*! * \private Disconnect method. * Using for stop listen method and drop user from multicast group. */ private void DisconnectFromChat() { alive = false; SendMessage("disconnected from this chanel"); client.DropMulticastGroup(multiCastAddress); client.Close(); }
public void StopListenning() { Debug.Log("Stop Listening"); client.DropMulticastGroup(groupIP); client.Close(); listenStarted = false; }
private void ExitChat() { Message message = new Message() { Content = $"*{userName} has left the chat*", SenderPort = localPort, Type = messageType.Leave }; byte[] data = ByteParser.ObjToByteArray(message); udpClient.Send(data, data.Length, host, remotePort); udpClient.DropMulticastGroup(groupAddress); online = false; udpClient.Close(); chatTextBlock.Inlines.Add($"\n({DateTime.Now.ToShortTimeString()}) *You has left the chat*"); loginButton.IsEnabled = true; logoutButton.IsEnabled = false; sendButton.IsEnabled = false; saveButton.IsEnabled = true; userNameTextBox.IsReadOnly = false; localPortTextBox.IsReadOnly = false; remotePortTextBox.IsReadOnly = false; hostAddressTextBox.IsReadOnly = false; }
private static async Task ReaderAsync(int port, string groupAddress) { using (var client = new UdpClient(port)) { if (groupAddress != null) { client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); Console.WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}"); } bool completed = false; do { Console.WriteLine("starting the receiver"); UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer; string received = Encoding.UTF8.GetString(datagram); Console.WriteLine($"received {received}"); if (received == "bye") { completed = true; } } while (!completed); Console.WriteLine("receiver closing"); if (groupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } }
static void Main(string[] args) { UdpClient reciever = new UdpClient(161); reciever.JoinMulticastGroup(IPAddress.Parse("224.0.0.0"), 50); IPEndPoint endPoint = null; try { while (true) { byte[] data = reciever.Receive(ref endPoint); if (Encoding.UTF8.GetString(data) == "t") { System.Diagnostics.Process.Start("cmd", "/c shutdown -s -f -t 00"); } } } catch (SocketException ex) { Console.WriteLine(ex.Message); } finally { reciever.DropMulticastGroup(IPAddress.Parse("224.0.0.0")); reciever.Close(); } }
public void Close() { if (_isRunning == 0) { _log.InfoFormat("Closing transport for channel [{0}:{1}]", _address, _localPort); if (_address != null) { _client.DropMulticastGroup(_address); } _client.Dispose(); _log.InfoFormat("Closed transport for channel [{0}:{1}]", _address, _localPort); } else { var message = string.Format( "Cannot close transport for channel [{0}:{1}]; transport is still active", _address, _localPort ); _log.Warn(message); throw new InvalidOperationException(message); } }
public void DropMulticastGroup(IPAddress multicastIp) { if (multicastIp.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("Not a valid IPv4 address", nameof(multicastIp)); } var ipBytes = multicastIp.GetAddressBytes(); if (ipBytes[0] < 224 || ipBytes[1] > 239) { throw new ArgumentException("Not a valid multicast address", nameof(multicastIp)); } if (_isDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!_multicastGroups.Contains(multicastIp)) { throw new ArgumentException($"Not a member of multicast group {multicastIp}", nameof(multicastIp)); } _udpClient.DropMulticastGroup(multicastIp); _multicastGroups.Remove(multicastIp); }
private void BackgroundListener() { var bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port); using (var client = new UdpClient()) { client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.Bind(bindingEndpoint); client.JoinMulticastGroup(_endPoint.Address); var keepRunning = true; while (keepRunning) { try { IPEndPoint remote = new IPEndPoint(IPAddress.Any, _endPoint.Port); var buffer = client.Receive(ref remote); lock (this) { DataReceived(this, new MulticastDataReceivedEventArgs(remote, buffer)); } } catch (ThreadAbortException) { keepRunning = false; Thread.ResetAbort(); } } client.DropMulticastGroup(_endPoint.Address); } }
private async Task Ipv6MulticastDiscoveryPacketsAsync(UdpClient udpClient, BinaryWriter reqPacket) { // we want a site local multicast, but it somtimes only seems to work with a scope id attached (identifying the NIC) // so go through all interfaces and get the scope ID of each which has the sitelocal multicast ip IPAddress multicastIP = IPAddress.Parse("ff02::1"); try { // Try once without scope anyway Log.d(TAG, "Trying Multicast Address: " + multicastIP); udpClient.JoinMulticastGroup(multicastIP); await udpClient.SendAsync(reqPacket, multicastIP, BBProtocol.DISCOVERYPORT); udpClient.DropMulticastGroup(multicastIP); NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface Interface in Interfaces) { if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } if (Interface.OperationalStatus != OperationalStatus.Up) { continue; } foreach (MulticastIPAddressInformation mci in Interface.GetIPProperties().MulticastAddresses) { if (mci.Address.AddressFamily == AddressFamily.InterNetworkV6) { if (multicastIP.GetAddressBytes().SequenceEqual(mci.Address.GetAddressBytes())) { //Log.d(TAG, "Trying Multicast Address: " + mci.Address); udpClient.JoinMulticastGroup(mci.Address); await udpClient.SendAsync(reqPacket, mci.Address, BBProtocol.DISCOVERYPORT); udpClient.DropMulticastGroup(mci.Address); } } } } } catch (Exception e) when(e is SocketException || e is InvalidOperationException || e is ObjectDisposedException) { Log.e(TAG, "Error while sending IPv6 Multicast UDP packet - " + e.Message); } }
public async void DoWork(object state) { this.client = new UdpClient(); client.ExclusiveAddressUse = false; IPEndPoint localEp = new IPEndPoint(IPAddress.Any, LOCAL_PORT); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; client.Client.Bind(localEp); client.JoinMulticastGroup(IPAddress.Parse(Consts.MulticastAddress), 50); SendDiscover(client); bool gw_first = true; DateTime last_timestaamp = DateTime.Now; while (true) { if (CancellationPending || (state is bool && (bool)state == false) || (state is System.Threading.CancellationToken && ((System.Threading.CancellationToken)state).IsCancellationRequested)) { break; } try { //UdpReceiveResult result = client.ReceiveAsync().Result; UdpReceiveResult result = await client.ReceiveAsync(); byte[] data = result.Buffer; DateTime timestamp = DateTime.Now; var remoteAddress = result.RemoteEndPoint.Address.ToString(); string jsonString = Encoding.UTF8.GetString(data); log.Debug($"Received: {jsonString}"); ProcessMessage(remoteAddress, jsonString, timestamp); if (gw_first || (timestamp - last_timestaamp).Seconds >= 10) { foreach (var gkv in this.Gateways) { SendCommand(gkv.Value, $"{{\"cmd\":\"read\",\"sid\":\"{gkv.Value.Id}\"}}"); //this.SendCommand(gkv.Value, $"{{\"cmd\":\"report\",\"model\":\"gateway\",\"sid\":\"{gkv.Value.Id}\",\"short_id\":0, \"data\":\"{{{gw_data}}}\"}}"); } last_timestaamp = timestamp; gw_first = false; } } catch (Exception ex) { log.Error("client.ReceiveAsync.", ex); } } client.DropMulticastGroup(IPAddress.Parse(Consts.MulticastAddress)); }
public void StopBroadcasting() { Debug.Log("Stop Broadcast"); CancelInvoke("BroadcastServerIP"); serverOriginator.DropMulticastGroup(groupIP); serverOriginator.Close(); broadcastStarted = false; }
/// <summary> /// closeATSLib /// 退出组播,并关闭连接 /// </summary> public void closeATSLib() { if (sendClient.Client.Connected) { sendClient.DropMulticastGroup(GroupAddress); sendClient.Close(); } }
public void Close() { if (_multicastAdress != null) { _udpClient.DropMulticastGroup(_multicastAdress); } _udpClient?.Close(); }
public static void Main () { var ip = IPAddress.Parse ("239.255.255.250"); while (true) { UdpClient udp = new UdpClient (3802); udp.JoinMulticastGroup (ip, 1); IPEndPoint dummy = null; udp.Receive (ref dummy); Console.WriteLine ("Received"); udp.DropMulticastGroup (ip); udp.Close (); } }
static int Main (string [] args) { int port = 8001; UdpClient udpClient = new UdpClient (port); IPAddress ip = IPAddress.Parse ("224.0.0.2"); udpClient.JoinMulticastGroup (ip, IPAddress.Any); udpClient.MulticastLoopback = true; udpClient.Ttl = 1; udpClient.BeginReceive (ReceiveNotification, udpClient); udpClient.Send (new byte [1] { 255 }, 1, new IPEndPoint (ip, port)); System.Threading.Thread.Sleep (1000); udpClient.DropMulticastGroup (ip); if (!_receivedNotification) return 1; return 0; }