// receive thread private void ReceiveData() { client = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port); client.Client.Bind(localEp); client.JoinMulticastGroup(IPAddress.Parse(MULTICAST_ADDR)); while (true) { try { byte[] data = client.Receive(ref localEp); string text = Encoding.UTF8.GetString(data); string[] message = text.Split(','); Vector3 result = new Vector3(float.Parse(message[0]), float.Parse(message[1]), float.Parse(message[2])); print(">> " + result); lastReceivedUDPPacket = result; } catch (Exception err) { print(err.ToString()); } } }
void StartListen() { // multicast receive setup remote_end = new IPEndPoint (IPAddress.Any, port); udp_client = new UdpClient (remote_end); udp_client.JoinMulticastGroup (group_address); // async callback for multicast udp_client.BeginReceive (new AsyncCallback (ReceiveAnnounceCallback), null); }
IEnumerator StartBroadcast() { // multicast send setup udp_client = new UdpClient (); udp_client.JoinMulticastGroup (group_address); IPEndPoint remote_end = new IPEndPoint (group_address, startup_port); // sends multicast while (true) { byte[] buffer = Encoding.ASCII.GetBytes ("GameServer"); udp_client.Send (buffer, buffer.Length, remote_end); yield return new WaitForSeconds (1); } }
void broadcast(string message) { // multicast send setup udp_client = new UdpClient (); udp_client.JoinMulticastGroup (group_address); remote_end = new IPEndPoint (group_address, port); byte[] buffer = Encoding.ASCII.GetBytes (message); udp_client.Send (buffer, buffer.Length, remote_end); }
public DiscoveryManager() { ActivityServices = new List<ServiceInfo>(); DiscoveryType = DiscoveryType.WsDiscovery; #if ANDROID _messageId = Guid.NewGuid().ToString(); _udpClient = new UdpClient(WsDiscoveryPort); _udpClient.JoinMulticastGroup(IPAddress.Parse(WsDiscoveryIPAddress)); _udpClient.BeginReceive(HandleRequest, _udpClient); #endif }
void RecieveCandidates() { IPEndPoint remote_end = new IPEndPoint (IPAddress.Any, startup_port); UdpClient udp_client = new UdpClient (remote_end); udp_client.JoinMulticastGroup (group_address); UdpState s = new UdpState(); s.e = remote_end; s.u = udp_client; // async callback for multicast udp_client.BeginReceive (new AsyncCallback (ServerLookup), s); }
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 (); } }
public Connector(string address, int port) { _dataBuffer = new byte[2048]; _address = address; _port = port; _multiCast = new IPEndPoint(IPAddress.Parse("239.0.0.1"), 9898); _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 9898)); _udpClient.JoinMulticastGroup(_multiCast.Address); Thread thread = new Thread(ReciveMessage); thread.Start(); }
// Constructor public static bool StartRecording(bool Is_ReplayFormat, string FilePath, // Path and file name IPAddress Interface_Addres, // IP address of the interface where the data is expected IPAddress Multicast_Address, // Multicast address of the expected data int PortNumber) // Port number of the expected data { if (IsConnectionActive() == false) { // Open up a new socket with the net IP address and port number try { rcv_sock = new UdpClient(); rcv_sock.ExclusiveAddressUse = false; rcv_iep = new IPEndPoint(IPAddress.Any, PortNumber); rcv_sock.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); rcv_sock.ExclusiveAddressUse = false; rcv_sock.Client.Bind(rcv_iep); rcv_sock.JoinMulticastGroup(Multicast_Address, Interface_Addres); } catch { MessageBox.Show("Not possible! Make sure given IP address/port is a valid one on your system or not already used by some other process"); return(false); } KeepGoing = true; RequestStop = false; ListenForDataThread = new Thread(new ThreadStart(DOWork)); ListenForDataThread.Start(); } RecordingEnabled = true; ReplayFormatRequested = Is_ReplayFormat; LastDataBlockDateTime = DateTime.Now; // Open up the stream try { RecordingStream = new FileStream(FilePath, FileMode.Create); RecordingBinaryWriter = new BinaryWriter(RecordingStream); } catch { } BytesProcessed = 0; return(true); }
// Listening for service announcement over UDP Multicast containing server address void listenForServiceReply() { var udpClient = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.ExclusiveAddressUse = false; udpClient.Client.Bind(localEp); IPAddress multicastAddress = IPAddress.Parse("239.255.255.250"); udpClient.JoinMulticastGroup(multicastAddress); while (true) { byte[] data = udpClient.Receive(ref localEp); var message = Encoding.UTF8.GetString(data, 0, data.Length); MLog(message); if (!message.ToLower().StartsWith("ml-stream-server")) { continue; } var parts = message.Split(' '); if (parts.Length < 2) { continue; } var address = parts[1].Split(':'); closeClient(); client = new TcpClient(); connectToServerBlocking(address[0], Convert.ToInt32(address[1])); if (socketConnected) { break; } } ssdpListenThread = null; }
// This example class demonstrates methods used to join and drop multicast groups. public static void MyUdpClientMulticastConfiguration(string myAction) { if (myAction == "JoinMultiCastExample") { //<Snippet12> UdpClient udpClient = new UdpClient(); IPAddress multicastIpAddress = Dns.Resolve("MulticastGroupName").AddressList[0]; try{ udpClient.JoinMulticastGroup(multicastIpAddress); } catch (Exception e) { Console.WriteLine(e.ToString()); } //</Snippet12> } else if (myAction == "JoinMultiCastWithTimeToLiveExample") { //<Snippet13> UdpClient udpClient = new UdpClient(); // Creates an IPAddress to use to join and drop the multicast group. IPAddress multicastIpAddress = IPAddress.Parse("239.255.255.255"); try{ // The packet dies after 50 router hops. udpClient.JoinMulticastGroup(multicastIpAddress, 50); } catch (Exception e) { Console.WriteLine(e.ToString()); } //</Snippet13> //<Snippet14> // Informs the server that you want to remove yourself from the multicast client list. try{ udpClient.DropMulticastGroup(multicastIpAddress); } catch (Exception e) { Console.WriteLine(e.ToString()); } //</Snippet14> //<Snippet15> // Closes the UDP client by calling the public method Close(). udpClient.Close(); //</Snippet15> } else { // Do nothing. } }
// 変更通知受信開始 private void Listen() { void func(IAsyncResult result) { var udpClient = ((UdpState)(result.AsyncState)).UdpClient; var ipEndPoint = ((UdpState)(result.AsyncState)).IpEndPoint; try { var data = udpClient.EndReceive(result, ref ipEndPoint); var receivedObject = XamlServices.Load(new MemoryStream(data)); if (receivedObject is DbChangeArgs args) { if (args.Source != this._identifier) { this._logger.Log(LogLevel.Notice, $"変更通知受信 {args.Source} : [{string.Join(", ", args.TableNames)}] [local:{ipEndPoint}]"); this._received.OnNext(args); } } } catch (Exception e) { this._logger.Log(LogLevel.Warning, $"変更通知受信失敗", e); this._error.OnNext(e); } udpClient.BeginReceive(func, new UdpState(udpClient, ipEndPoint)); } foreach (var address in this._nicAddresses) { IPAddress remoteAddress = null; var port = 0; if (address.Address.AddressFamily == AddressFamily.InterNetwork) { port = this._ipv4Port; remoteAddress = this._ipv4Address; } else if (address.Address.AddressFamily == AddressFamily.InterNetworkV6) { port = this._ipv6Port; remoteAddress = this._ipv6Address; } else { continue; } var ipEndPoint = new IPEndPoint(address.Address, port); var client = new UdpClient(ipEndPoint); client.JoinMulticastGroup(remoteAddress); client.BeginReceive(func, new UdpState(client, ipEndPoint)); } }
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 void Main(string[] args) { UdpClient client = new UdpClient(10000); client.JoinMulticastGroup(IPAddress.Parse("239.255.255.250")); IPEndPoint multicast = new IPEndPoint(IPAddress.Any, 0); while (true) { byte[] buf = client.Receive(ref multicast); string msg = Encoding.Default.GetString(buf); Console.WriteLine(msg); Console.WriteLine(multicast); } }
private void SendMulticast(VisorData datos) { //enviar por udp UdpClient udpclient = new UdpClient(); IPAddress multicastaddress = IPAddress.Parse("239.239.239.239"); udpclient.JoinMulticastGroup(multicastaddress); IPEndPoint remoteep = new IPEndPoint(multicastaddress, 7001); byte[] buffer = null; Encoding enc = Encoding.Unicode; buffer = ObjectToByteArray(datos); udpclient.Send(buffer, buffer.Length, remoteep); }
public SsdpHandler() { notificationTimer.Elapsed += Tick; notificationTimer.Enabled = true; queueTimer.Elapsed += ProcessQueue; client.Client.UseOnlyOverlappedIO = true; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; client.Client.Bind(new IPEndPoint(IPAddress.Any, SSDP_PORT)); client.JoinMulticastGroup(SSDP_IP, 2); Notice("SSDP service started"); Receive(); }
/// <summary> /// Constructor : create UdpClient .. /// 한컴퓨터에서 여러개의 멀티캐스트를 실행할경우 bind포트가 겹치므로 port번호는 서버에서 생성한것으 받아옴) /// </summary> /// <param name="port"></param> public static void CreateUDPClient(int port) { serverEP = new IPEndPoint(IPAddress.Parse(NetworkManagerTCP.ip), port); multicastPort = port; //receive client local ip 접속 clientUDP = new UdpClient(); //Socket option clientUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); Debug.Log("Port : " + multicastPort); clientEP = new IPEndPoint(IPAddress.Any, multicastPort); clientUDP.Client.Bind(clientEP); //멀티캐스트 접속 clientUDP.JoinMulticastGroup(IPAddress.Parse(multicastIP)); BeginMulticastReceive(); }
private void InitUdpClient() { try { _udpClient = new UdpClient(AddressFamily.InterNetwork); _udpClient.JoinMulticastGroup(_generationConfig.MulticastGroup); } catch (SocketException e) { Console.WriteLine( $"Impossible to initialize the UDP client: {e.Message}.\nOperation will repeat in {RECONNECT_DELAY_MS / 1000} seconds..."); Thread.Sleep(RECONNECT_DELAY_MS); InitUdpClient(); } }
static void StartListener() { recvClient.ExclusiveAddressUse = false; IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 1993); recvClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); recvClient.Client.Bind(localEp); IPAddress multicastAddress = IPAddress.Parse("239.0.0.118"); recvClient.JoinMulticastGroup(multicastAddress); recvClient.BeginReceive(new AsyncCallback(ReceiveMessage), null); }
public MulticastLogger(IPAddress MulticastIPaddress, int Port) : base() { IPEndPoint localEndPoint; this.multicastIPaddress = MulticastIPaddress; localEndPoint = new IPEndPoint(IPAddress.Any, 0); remoteEndPoint = new IPEndPoint(MulticastIPaddress, Port); client = new UdpClient(AddressFamily.InterNetwork); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; //client.Client.Bind(localEndPoint); client.JoinMulticastGroup(MulticastIPaddress, IPAddress.Any); }
private static void multicastWsPort() { bytesToSend = Encoding.ASCII.GetBytes(wsPort); // Buttons should connect to websocket at the port number broadcasted udpClient = new UdpClient(); IPAddress multicastAddress = IPAddress.Parse("239.1.1.234"); udpClient.JoinMulticastGroup(multicastAddress); remoteEp = new IPEndPoint(multicastAddress, 4210); // Send multicast to this address and port DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += dispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 2); // Send every 2 seconds dispatcherTimer.Start(); }
private UdpClient GetSendClient() { lock (_lockerSend) { if (_clientSend == null) { _clientSend = new UdpClient(); if (IsMulticast()) { _clientSend.JoinMulticastGroup(RemoteAddress); } } } return(_clientSend); }
public void Listen() { foreach (var IP in (from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip.ToString()).ToList()) { UdpClient UdpClient = new UdpClient(); UdpClient.AllowNatTraversal(true); LocalEntryPoint = new IPEndPoint(IPAddress.Parse(IP), MulticastAddress.Port); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); UdpClient.Client.Bind(LocalEntryPoint); UdpClient.JoinMulticastGroup(MulticastAddress.Address, IPAddress.Parse(IP)); UdpClient.BeginReceive(ReceiveCallBack, new object[] { UdpClient, new IPEndPoint(IPAddress.Parse(IP), ((IPEndPoint)UdpClient.Client.LocalEndPoint).Port) }); } }
public Connection(int port) { this.port = port; multicastaddress = IPAddress.Parse("239.0.0.222"); udpclient = new UdpClient(); remoteep = new IPEndPoint(multicastaddress, port); localEp = new IPEndPoint(IPAddress.Any, port); udpclient.JoinMulticastGroup(multicastaddress); udpclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpclient.ExclusiveAddressUse = false; udpclient.Client.Bind(localEp); udpclient.Client.Ttl = 1; Send("Send first message", port); }
private void RecreateSender() { // Recreate the sender if (sender != null) { sender.Dispose(); } sender = new UdpClient(mdnsEndpoint.AddressFamily); if (IsUsingSingleInterface) { RestrictToNetworkInterface(sender, knownNics.First()); } sender.JoinMulticastGroup(mdnsEndpoint.Address); sender.MulticastLoopback = true; }
/// <summary> /// Initializing UDP client for listening Multicast Group /// </summary> private void InitializeUdpClient() { _udpServerClient = new UdpClient { ExclusiveAddressUse = false }; _ipEndPoint = new IPEndPoint(IPAddress.Any, Program.MulticastGroupPort); _udpServerClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpServerClient.Client.Bind(_ipEndPoint); var multicastAddress = IPAddress.Parse(Program.MulticastGroupIp); _udpServerClient.JoinMulticastGroup(multicastAddress); }
static void Main123(string[] args) { var udpClient = new UdpClient(); var ip = IPAddress.Parse("224.5.6.7"); udpClient.JoinMulticastGroup(ip); var ep = new IPEndPoint(ip, 45678); while (true) { var str = Console.ReadLine(); var bytes = Encoding.Default.GetBytes(str); udpClient.Send(bytes, bytes.Length, ep); } }
internal PlayerListCoordinator(PlayerListViewModel listViewModel, PlayerDataViewModel dataViewModel, Action <UdpWrapper <GamePacket> > onJoinGameEvent) { _playerView = listViewModel; _playerDataBox = dataViewModel; { UdpClient multicastClient = new UdpClient(Config.MulticastEndPoint.Port); multicastClient.JoinMulticastGroup(Config.MulticastEndPoint.Address); multicastClient.MulticastLoopback = true; _multicaster = new UdpWrapper <Player>(multicastClient, Config.MulticastEndPoint, false); } _invitationManager = new InvitationManager(); _invitationManager.JoinGameEvent += onJoinGameEvent; _playerDataBox.SetPublicEndPoint(_invitationManager.ListenerEndPoint); }
public M_Multi_Cast() { multiAddress = IPAddress.Parse("238.228.218.208"); multiPort = 12321; multicastEnd = new IPEndPoint(IPAddress.Parse("238.228.218.208"), 12321); client = new UdpClient(12321); client.JoinMulticastGroup(IPAddress.Parse("238.228.218.208")); tcpServer = new IPEndPoint(IPAddress.Parse("10.10.100.100"), 6000); command = new byte[] { 0x3A, 0xA3, 0x28, 0x00, 0x00, 0xA4, 0x50, 0x01, 0x70, 0x17, 0x0A, 0x0A, 0x64, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC3 }; }
public void CreateServer() { try { IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222); IPAddress multicastaddress = IPAddress.Parse("239.0.0.222"); udpServer.JoinMulticastGroup(multicastaddress); udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpServer.Client.Bind(localEp); } catch (Exception e) { Console.WriteLine("Exception 3 : " + e); } }
[Test] // JoinMulticastGroup (IPAddress) public void JoinMulticastGroup1_MulticastAddr_Null() { using (UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 1234))) { try { client.JoinMulticastGroup((IPAddress)null); Assert.Fail("#1"); #if NET_2_0 } catch (ArgumentNullException ex) { Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2"); Assert.IsNull(ex.InnerException, "#3"); Assert.IsNotNull(ex.Message, "#4"); Assert.AreEqual("multicastAddr", ex.ParamName, "#5"); } #else } catch (NullReferenceException ex) {
[Test] // JoinMulticastGroup (IPAddress) public void JoinMulticastGroup1_IPv6() { #if NET_2_0 if (!Socket.OSSupportsIPv6) #else if (!Socket.SupportsIPv6) #endif { Assert.Ignore("IPv6 not enabled."); } IPAddress mcast_addr = IPAddress.Parse("ff02::1"); using (UdpClient client = new UdpClient(new IPEndPoint(IPAddress.IPv6Any, 1234))) { client.JoinMulticastGroup(mcast_addr); } }
public static void Main() { UdpClient sock = new UdpClient(9050); Console.WriteLine("Ready to receive..."); sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); byte[] data = sock.Receive(ref iep); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString()); sock.Close(); }
IEnumerator SendCandidate() { // multicast send setup UdpClient udp_client = new UdpClient (); udp_client.JoinMulticastGroup (group_address); IPEndPoint remote_end = new IPEndPoint (group_address, startup_port); // sends multicast while (true) { byte[] buffer = Encoding.ASCII.GetBytes (SystemInfo.deviceUniqueIdentifier); udp_client.Send (buffer, buffer.Length, remote_end); yield return new WaitForSeconds (1); } }
public UdpBroadcastForWindows(string multicastIp, int port) { this.multicastIp = multicastIp; this.port = port; UdpClient = new UdpClient(); UdpClient.EnableBroadcast = true; UdpClient.Client.Bind(new IPEndPoint(IPAddress.Any, port)); UdpClient.Client.SendTimeout = 500; UdpClient.Client.ReceiveTimeout = 500; UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); UdpClient.JoinMulticastGroup(IPAddress.Parse(multicastIp)); }
public ServerListBackend() { GameHost.AnyGameStateChanged += ThisHostStateChanged; udp = new UdpClient(); udp.ExclusiveAddressUse = false; udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udp.JoinMulticastGroup(multicastaddress); udp.Client.Bind(new IPEndPoint(IPAddress.Any, MyCommunicationPort)); var listenerThread = new Thread(this.listenerThread); listenerThread.IsBackground = true; listenerThread.Start(); }
private void ReceiveConnection(ListBox lb) { UdpClient client = new UdpClient(8005); client.JoinMulticastGroup(IPAddress.Parse("230.230.230.230"), 50); IPEndPoint remoteIp = null; try { while (!token.IsCancellationRequested) { byte[] data = client.Receive(ref remoteIp); TalkPacket msg = new TalkPacket(data); Sub sub = new Sub(msg.Data.ToString(), remoteIp); if (msg.Type == 1) { if (!Subs.Contains(sub)) { Subs.Add(sub); } lb.Items.Add(" " + sub.name + " присоединился к разговору."); TcpClient sender = new TcpClient(remoteIp); NetworkStream stream = sender.GetStream(); msg = new TalkPacket(1, UserName); stream.Write(msg.getBytes(), 0, msg.MsgLength); stream.Close(); sender.Close(); } else if (msg.Type == 0) { if (Subs.Contains(sub)) { Subs.Remove(sub); lb.Items.Add(" " + sub.name + " покинул нас."); } } else { MessageBox.Show("An error occured!"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } client.Close(); }
// receive thread private void ReceiveData() { port = 8051; client = new UdpClient(port); if (multicastGroupAddress != null) { client.JoinMulticastGroup(multicastGroupAddress); } print("Starting Server"); while (receiveThread != null) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); String device = System.Text.Encoding.Default.GetString(data, 0, 31); if (device.IndexOf(deviceFilter) >= 0) { rotationMode = (RotationMode)data[31]; translation.x = (float)BitConverter.ToDouble(data, 32 + 0 * 8); translation.y = (float)BitConverter.ToDouble(data, 32 + 1 * 8); translation.z = (float)BitConverter.ToDouble(data, 32 + 2 * 8); switch (rotationMode) { case RotationMode.ROTATION_MODE_EULER: eulerRotation.x = (float)BitConverter.ToDouble(data, 32 + 3 * 8); eulerRotation.y = (float)BitConverter.ToDouble(data, 32 + 4 * 8); eulerRotation.z = (float)BitConverter.ToDouble(data, 32 + 5 * 8); break; case RotationMode.ROTATION_MODE_QUATERNION: quaternion.w = (float)BitConverter.ToDouble(data, 32 + 3 * 8); quaternion.x = (float)BitConverter.ToDouble(data, 32 + 4 * 8); quaternion.y = (float)BitConverter.ToDouble(data, 32 + 5 * 8); quaternion.z = (float)BitConverter.ToDouble(data, 32 + 6 * 8); break; } } } catch (Exception err) { print(err.ToString()); } } }
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; }
void ListenWorker(Action<byte[]> callback, string address, int port) { using (UdpClient listener = new UdpClient(port)) { IPAddress addr = IPAddress.Parse(address); IPEndPoint ep = new IPEndPoint(addr, port); listener.JoinMulticastGroup(addr); //listener.Client.ReceiveBufferSize = 16*4096; Debug.Log("Listening on " + address + ":" + port.ToString()); List<byte> lastData = new List<byte>(); while (!die) { byte[] data = listener.Receive(ref ep); received += data.Length; byte[] before; byte[] after; FindBeforeAndAfterSignal(data, out before, out after); bool send = (lastData != null && before == null) || (before != null && before.Length != data.Length); if (before != null) lastData.AddRange(before); if (send) { if (lastData != null && lastData.Count > 0) { callback(lastData.ToArray()); } if (after != null) lastData = new List<byte>(after); else lastData = new List<byte>(); } } } }
void WriteWorker(string address, int port) { using (UdpClient writer = new UdpClient()) { var ip = IPAddress.Parse(address); writer.JoinMulticastGroup(ip); //writer.Client.SendBufferSize = 16*4096; var ipEndPoint = new IPEndPoint(ip, port); Debug.Log("writing to " + address + ":" + port.ToString()); writer.Send(signal, signal.Length, ipEndPoint); while (!die) { byte[] next = null; lock(toSendLock) if (toSend.Count > 0) { next = toSend.Pop(); } if (next != null) { Debug.Log("Sending data " + next.Length); //writer.BeginSend(next, next.Length, null, null); for(int i = 0; i < next.Length; i += 1024) { int amount = i < next.Length - 1024 ? 1024 : next.Length - i; byte[] send = new byte[amount]; System.Array.Copy(next, i, send, 0, amount); writer.Send(send, send.Length, ipEndPoint); sent += amount; } //writer.Send(next, next.Length, ipEndPoint); } Thread.Sleep(50); } } }
}//Terminate() public static void Initialize() { // // instantiate UdpCLient // m_Client = new UdpClient(LocalPort); // // Create an object for Multicast Group // m_GroupAddress = IPAddress.Parse("224.0.0.1"); // // Join Group // try { m_Client.JoinMulticastGroup(m_GroupAddress, 100); }//try catch(Exception e) { Console.WriteLine("Unable to join multicast group: {0}", e.ToString()); }//catch // // Create Endpoint for peer // m_RemoteEP = new IPEndPoint(m_GroupAddress, RemotePort); }//Initialize()
private async Task OpenMulticastSocket(HostInfo hostInfo, bool ipv6) { if (group == null) { // TODO: not going to resolve this, just going to set it directly //group = Dns.Resolve(DNSConstants.MDNS_GROUP).AddressList[0]; group = IPAddress.Parse(ipv6 ? DNSConstants.MDNS_GROUP_IPV6 : DNSConstants.MDNS_GROUP); } if (socket != null) { await this.CloseMulticastSocket(); } socket = new UdpClient(DNSConstants.MDNS_PORT); await socket.Bind(); socket.JoinMulticastGroup((IPAddress) group, 255); }
void StartGameClient() { // multicast receive setup IPEndPoint remote_end = new IPEndPoint (IPAddress.Any, startup_port); udp_client = new UdpClient (remote_end); udp_client.JoinMulticastGroup (group_address); // async callback for multicast udp_client.BeginReceive (new AsyncCallback (ServerLookup), null); StartCoroutine(MakeConnection ()); }