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

(急)udpClient.Receive(ref remotePoint)一直提示“在执行此操作前必须先调用 Bind 方法。”
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Data;
using System.Windows.Forms;

namespace UDP
{
  public class UDPClient
  {
  //设置一个timer,在发送或get数据的时候,判断5秒没有数据返回,则报连接不上
  System.Timers.Timer timer = new System.Timers.Timer();

  private IPEndPoint hostPoint;//服务器主机地址
  private IPEndPoint remotePoint;//目标主机地址

  private Thread listenThread;//监听线程
  private UdpClient udpClient;

  private bool bConnect = false;

  public bool BConnect
  {
  get { return bConnect; }
  set { bConnect = value; }
  }

  //类当前的状态
  public UDPRETURNTYPE currenttype = UDPRETURNTYPE.NULL;

  //singleton模式
  private static UDPClient theclient;

  //不可不带参数实例化
  private UDPClient()
  {

  }

  public static UDPClient instance(string ip)
  {
  theclient = new UDPClient(ip, "5006");
  return theclient;
  }
  ~UDPClient()
  {
  try
  {
  udpClient.Close();
  listenThread.Abort();

  }
  catch
  { }
  }

  public void Close()
  {
  try
  {
  udpClient.Close();
  listenThread.Abort();

  }
  catch
  { }
  }

  private UDPClient(string pserverIP, string pserverPort)
  {
  if (this.udpClient != null)
  {
  udpClient.Close();
  udpClient = null;
  }
  //Console.WriteLine("我是客户端,我开始运行啦11!");
  string serverIp = pserverIP;
  int Port = int.Parse(pserverPort);
  udpClient = new UdpClient();
  remotePoint = new IPEndPoint(IPAddress.Any, 0);//提供任何端口和IP,这里不需要指定
  hostPoint = new IPEndPoint(IPAddress.Parse(serverIp), Port);//实例化主机地址

  //=========================一开始测试发送==========================
  byte[] buffer;
  buffer = System.Text.Encoding.UTF8.GetBytes(Convert.ToString((int)UDPTYPE.connect));

  listenThread = new Thread(new ThreadStart(Run));
  listenThread.Start();
  this.timer.Interval = 500;
  this.timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
  }

  int itime = 0;
  void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  {

  if (itime >= 3000 && this.currenttype == UDPRETURNTYPE.NULL)
  {
  itime = 0;
  timer.Stop();
  MessageBox.Show(" 与上级计算机无法正常连接,请检查\r“数据传输地址”是否错误或联系管理员!");

  }
  else if (this.currenttype == UDPRETURNTYPE.SUCCESS)
  {