日期:2014-05-18  浏览次数:20976 次

关于UDP的 求助!!!
服务器端的代码如下:
  public class Class1
  {
  static void Main(string[] args)
  {
  Custom.StartListener();
  }
  }
  public class Custom
  {
  private static readonly IPAddress GroupAddress = IPAddress.Parse("127.0.0.1");
  private const int GroupPort = 11000;

  public static void StartListener()
  {
  //bool done = false;
  UdpClient listener = new UdpClient();
  IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
  try
  {
  //listener.JoinMulticastGroup(GroupAddress);
  listener.Connect("127.0.0.1",11000);
  while (true)
  {
  Console.WriteLine("Waiting for broadcast");
  byte[] bytes = listener.Receive(ref groupEP);
  Console.WriteLine("Received broadcast from {0} :\n {1}\n",
  groupEP.Address.ToString(),
  Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  }
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }
   
  }

客户端的代码:
 public class Client
  {
  static void Main(string[] args)
  {
  Console.WriteLine("输入数据");
  Send(Console.ReadLine());
  Console.ReadLine();  
  }

  private static IPAddress GroupAddress = IPAddress.Parse("127.0.0.1");
  private static int GroupPort = 11000;
  private static void Send(string message)
  {
  UdpClient sender = new UdpClient();
  IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
   
  try
  {
  Console.WriteLine("Sending datagram : {0}", message);
  byte[] bytes = Encoding.ASCII.GetBytes(message);
  sender.Send(bytes, bytes.Length, "192.168.0.16", 4567);
  sender.Close();
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }

  }

现在有问题了,我服务器接收不到数据。。求大侠指教啊。。小弟先行感谢了,!

------解决方案--------------------
客户端不要指定端口,而且你这服务端和客户端端口都一样,肯定不行的
------解决方案--------------------
Connect 是发送用的
C# code
// 服务端方法
public static void StartListener()
{
    UdpClient listener = new UdpClient(GroupPort);
    IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
    try
    {
        while (true)
        {
            Console.WriteLine("Waiting for broadcast");
            byte[] bytes = listener.Receive(ref groupEP);
            Console.WriteLine("Received broadcast from {0} :\n {1}\n",
            groupEP.Address.ToString(),
            Encoding.ASCII.GetString(bytes, 0, bytes.Length));
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

// 客户端方法
private static void Send(string message)
{
    UdpClient sender = new UdpClient();
    IPEndP