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

UdpClient 的用法问题,愁死了,请大家帮忙。

这是在本机做的一个程序用作测试。本机的IP为127.0.0.1吧。
请大家帮我分析一下,这些问题让我很郁闷,心理很憋屈,这到底是怎么回事啊?
问题都在注释中。

服务器端 :
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace UDPServer
{
  class Program
  {
  static void Main(string[] args)
  {
  UdpClient receivingUdpClient = new UdpClient(12222);

  IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
  //问题一
//第二个参数0 不是说只要有效的端口都可以接收数据吗?为什么客户端的端口不等于12222的时候就接收不到数据了呢?
//问题二
//IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("124.110.0.1"), 0);//胡乱写的IP地址也能收到数据,郁闷。
//这里的"124.110.0.1",不是指定只接收这个IP地址的数据吗?那为什么这个可以接收到数据。
  while (true)
  {
  try
  {
  Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
  if (receiveBytes.GetLength(0) > 0)
  {
  string returnData = Encoding.ASCII.GetString(receiveBytes);
   
  Console.WriteLine("This is the message you received " +
  returnData.ToString());
  Console.WriteLine("This message was sent from " +
  RemoteIpEndPoint.Address.ToString() +
  " on their port number " +
  RemoteIpEndPoint.Port.ToString());
  }
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }

  }
  }

}

客户端:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace UDPClient
{
  class Program
  {
  static void Main(string[] args)
  {
  UdpClient udpClient = new UdpClient();
  Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there");
  try
  {
  udpClient.Send(sendBytes, sendBytes.Length,"127.125.100.100", 12222);
  //"127.125.100.100"不是指定的目的机的IP吗?结果发现只要第一个端的地址为127都可以发送成功,服务端也都可以接收到数据。为什么? }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  Console.ReadLine();
  }
  }

}

------解决方案--------------------
//第二个参数0 不是说只要有效的端口都可以接收数据吗?为什么客户端的端口不等于12222的时候就接收不到数据了呢? 
因为你的客户端是发给12222端口的 你的server也得在这个端口接收 因为你是个server 
如果你是client的话可以随便选个端口就可以 因为他是先随机选择一个端口发送给server 然后因为server是通过Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); 来接收数据的 也就知道了client选择的随即端口号是多少 IP地址是多少 就可以通过这个RemoteIpEndPoint来给客户端发送了 因为收数据必须在明确的端口号 发数据必须发往明确的端口号 至于随便绑定一个IP就不清楚了