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

socket 异步接收不到数据问题
代码如下:
  public void CommuniteHelp_TCP()
  {
  while (true)
  {
  try
  {
  MREvent.Reset();
  tcpListener.BeginAcceptTcpClient(new AsyncCallback(AsynAccept), tcpListener);
  MREvent.WaitOne();

  }
  catch (Exception ex)
  {
  System.Diagnostics.Debug.Print("运行方法: CommuniteHelp 发生错误:" + ex.Message);
  }

  }
  }

  private void AsynAccept(IAsyncResult mtcplisten) 
  {
  TcpListener mtcpListener = (TcpListener)mtcplisten.AsyncState;
  TcpClient mtcpClient = mtcpListener.EndAcceptTcpClient(mtcplisten);
  MREvent.Set();
  Thread thread_dotcp = new Thread(new ParameterizedThreadStart(ThreadAsynReceiveData));
  thread_dotcp.IsBackground = true;
  thread_dotcp.Start(mtcpClient);
   
  }
  private void ThreadAsynReceiveData(object mobj)
  {
  TcpClient mtcpClient = mobj as TcpClient;
  byte[] receiveBytes = new byte[1024];

  mtcpClient.Client.BeginReceive(receiveBytes, 0, 1024, SocketFlags.None, new AsyncCallback (doneAsynAccept), mtcpClient);


  }
private void doneAsynAccept(IAsyncResult iar)
  {
  try
  {
  lock (lockobj)
  {
  TcpClient mtcpClient = (TcpClient)iar.AsyncState;
  int dataCount = mtcpClient.Client.EndReceive(iar);
  if (dataCount > 0)
  {
  byte[] receiveBytes = new byte[dataCount];
  IAsyncResult Result= mtcpClient.Client.BeginReceive(receiveBytes, 0, dataCount, SocketFlags.None, new AsyncCallback(doneAsynAccept), mtcpClient); // 这里接收不到数据,请问为什么?
   
  StructModel.tcpSendTo tcpsendto = new StructModel.tcpSendTo();
  tcpsendto.point = ((IPEndPoint)mtcpClient.Client.RemoteEndPoint);
  tcpsendto.oreceiveBytes = receiveBytes;
  tcpsendto.receiveBytesLength = (ushort)dataCount;
  tcpsendto.ns = mtcpClient.GetStream();
  tcpsendto.tcpClient = mtcpClient;
  DoWork(tcpsendto);
  }
   
   
  //mtcpClient.Close();
  //mtcpClient = null;
  }
  }
  catch (Exception ee)
  {

  ErrorLog.WriteErrorLog("CRTUClient_Udp:CRTUClient", "DoWork", "", ee);
  }
  finally
  {
  GC.Collect();
  Thread.CurrentThread.Abort();
  }

  }

------解决方案--------------------
receiveBytes定义为窗体变量,不是函数变量. dataCount > 0时 receiveBytes就已经收到数据了.