using System; using System.Net; using System.Net.Sockets; using System.Text; public class Client { private static IPAddress GroupAddress = IPAddress.Parse("224.168.100.2"); private static int GroupPort = 3000; private static void Send(String message) { UdpClient sender = new UdpClient(); IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort); try { Console.WriteLine("Input Sending datagram :"); message= Console.ReadLine(); byte[] bytes = Encoding.ASCII.GetBytes(message); sender.Send(bytes, bytes.Length, groupEP); sender.Close(); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { Send("ceshi"); return 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Custom { public class Custom { private static readonly IPAddress GroupAddress = IPAddress.Parse("224.168.100.2"); private const int GroupPort = 3000; private static void StartListener() { bool done = false; UdpClient listener = new UdpClient(); IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort); try { //listener.EnableBroadcast = true; listener.JoinMulticastGroup(GroupAddress); listener.Connect(groupEP); while (!done) { Console.WriteLine("Waiting for broadcast"); byte[] bytes = listener.Receive(ref groupEP); Console.WriteLine("Received broadcast from {0} :\n {1}\n", groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } listener.Close(); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { StartListener(); return 0; } } }
不知道怎么回事,在消息发送端,发送消息,消息接收端,就是没反应,很是郁闷,请大侠们看看.谢谢..
发送的时候,可能也要先加入的广播组中
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Custom { public class Custom { private static readonly IPAddress GroupAddress = IPAddress.Parse("224.168.100.2"); private const int GroupPort = 3000; private static void StartListener() { bool done = false; UdpClient listener = new UdpClient(GroupPort ); IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort); try { listener.JoinMulticastGroup(GroupAddress); while (!done) { Console.WriteLine("Waiting for broadcast"); byte[] bytes = listener.Receive(ref groupEP); Console.WriteLine("Received broadcast from {0} :\n {1}\n", groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } listener.Close(); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { StartListener(); return 0; } } }
自己解决了,组播发送的时候,接收端不能使用udpclient的Connect方法