private void AUDPRecieve(IAsyncResult iar)
        {
            UDPState state      = (UDPState)iar.AsyncState;
            Socket   mySocket   = state.workSocket;
            int      dataLength = mySocket.EndReceiveFrom(iar, ref state.endPoint);

            state.data = Encoding.ASCII.GetString(state.buffer, 0, dataLength);

            System.Console.WriteLine(state.endPoint.ToString() + " say :" + state.data);



            recieveDone.Set();
        }
        public void ConnectServer()
        {
            string sendData = "Hello Server......";

            byte[] sendBuffer = new byte[1024];
            sendBuffer = Encoding.ASCII.GetBytes(sendData);
            clientSocket.BeginSendTo(sendBuffer, 0, sendBuffer.Length, 0, (EndPoint)endPoint, new AsyncCallback(AUDPSend), clientSocket);
            sendDone.WaitOne();

            UDPState state = new UDPState();

            state.workSocket = clientSocket;
            state.endPoint   = (EndPoint)(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0));
            clientSocket.BeginReceiveFrom(state.buffer, 0, state.BufferSize(), 0, ref state.endPoint, new AsyncCallback(AUDPRecieve), state);
            recieveDone.WaitOne();

            sendDone.Reset();
            string sendData2 = "END";

            byte[] sendBuffer2 = new byte[1024];
            sendBuffer2 = Encoding.ASCII.GetBytes(sendData2);
            clientSocket.BeginSendTo(sendBuffer2, 0, sendBuffer2.Length, 0, (EndPoint)endPoint, new AsyncCallback(AUDPSend), clientSocket);
            sendDone.WaitOne();
        }
Esempio n. 3
0
        public void StartServer()
        {
            serverSocket.Bind(endPoint);
            System.Console.WriteLine("服务器开启,等待数据.........");

            startTime = DateTime.Now;

            UDPState state = new UDPState();

            state.workSocket = serverSocket;
            state.endPoint   = (EndPoint)remoteEndPoint;
            serverSocket.BeginReceiveFrom(state.buffer, 0, state.BufferSize(), 0, ref state.endPoint, new AsyncCallback(AUDPRecieve), state);
            recieveDone.WaitOne();

            string sendData = "I Have Got It!";

            byte[] sendBuffer = new byte[1024];
            sendBuffer = Encoding.ASCII.GetBytes(sendData);
            serverSocket.BeginSendTo(sendBuffer, 0, sendBuffer.Length, 0, state.endPoint, new AsyncCallback(AUDPSend), serverSocket);
            sendDone.WaitOne();

            state = new UDPState();
            recieveDone.Reset();
            state.workSocket = serverSocket;
            state.endPoint   = (EndPoint)remoteEndPoint;
            serverSocket.BeginReceiveFrom(state.buffer, 0, state.BufferSize(), 0, ref state.endPoint, new AsyncCallback(AUDPRecieve), state);
            recieveDone.WaitOne();

            endTime = DateTime.Now;

            TimeSpan span = endTime - startTime;

            System.Console.WriteLine("通信结束..........");

            System.Console.WriteLine("使用时间(微秒):" + span.TotalMilliseconds);
        }