private void ReceiveFromCallback(IAsyncResult ar) { UDPClientStateObject so = (UDPClientStateObject)ar.AsyncState; Socket socket = so.workSocket; IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tempRemoteEP = (EndPoint)sender; int receivedDataLength = socket.EndReceiveFrom(ar, ref tempRemoteEP); so.tempRemoteEP = tempRemoteEP; ReceiveEvent(so);//...交由外部處理 //_receiveDone.Set(); }
public void BeginReceive() { //_receiveDone.Reset(); //...建立接收的位置, 所有 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); //...返回對方的位置 EndPoint remoteEP = (EndPoint)(sender); UDPClientStateObject stateObject = new UDPClientStateObject(); stateObject.workSocket = _server; stateObject.receiveBuffer = new byte[_receiveBuffer]; _server.BeginReceiveFrom(stateObject.receiveBuffer, 0, _receiveBuffer, 0, ref remoteEP, new AsyncCallback(ReceiveFromCallback), stateObject); //_receiveDone.WaitOne(); }