示例#1
0
 private void AsyncCallback(IAsyncResult ar)
 {
     if ("".Equals(callback_error) == false)
     {
         pFrmApp.JS_Function(this.callback_error, ar.ToString());
     }
 }
示例#2
0
        public static void ListenerCallback(IAsyncResult result)
        {
            var context = _listener.EndGetContext(result);

            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            if (uris.Contains(request.Url.ToString()))
            {
                context.Response.StatusCode        = 200;
                context.Response.StatusDescription = "OK";

                Console.WriteLine(result.ToString());

                string responseString = "<HTML><BODY> YOU ASKED FOR:" + request.Url + "</BODY></HTML>";
                byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
                context.Response.Close();
            }

            else
            {
                context.Response.StatusCode        = 404;
                context.Response.StatusDescription = "NOT FOUND";
                context.Response.Close();
            }
        }
示例#3
0
        /// <summary>
        /// Metodo AcceptCallBack: Metodo en el cual se recibe la solicitud desde cliente y se atiende
        /// </summary>
        /// <param name="ar"></param>
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket client = serverSocket.EndAccept(ar);

            clients.Add(client);
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReciveCallback), client);
            Accept();
            Program.AddLog(ar.ToString());
        }
示例#4
0
        /// <summary>
        /// Complements BeginStopLogging
        /// </summary>
        public void EndStopLogging(IAsyncResult asyncResult)
        {
            Trace.WriteLine("SsmBasicLogger.EndStopLogging");
            // No-op, just here to complete the async pattern

            // Make StyleCop happy:
            asyncResult.ToString();
            this.ToString();
        }
		public void CB(IAsyncResult ar)
		{
			// this will be executed in another thread
			t.Tim = ar.ToString();
			ad.EndInvoke(ar);
			syncContext.Post(delegate(object state)
			{
				// This will be executed again in form thread
				lbl_time.Text = t.Tim;
			}, null);
		}
示例#6
0
            public TimeoutItem(long expires, IAsyncResult asyncResult, IDisposable disposable)
            {
                if (asyncResult == null)
                {
                    throw new ArgumentNullException(asyncResult.ToString());
                }

                Expires     = expires;
                AsyncResult = asyncResult;
                Disposable  = disposable;
            }
示例#7
0
        private void AcceptCallback(IAsyncResult ar)
        {
            Console.WriteLine("开始异步Accept");
            Socket clientSocket = serverSocket.EndAccept(ar);

            Console.WriteLine("[ar]" + ar.ToString());
            Client client = new Client(clientSocket, this);

            clientList.Add(client);
            Console.WriteLine($"[clientList]容量{clientList.Count}");
            serverSocket.BeginAccept(AcceptCallback, null);
        }
示例#8
0
        /// <summary>
        /// 异步接收客户端里阿尼额
        /// </summary>
        /// <param name="ar"></param>
        private void AcceptCallBack(IAsyncResult ar)
        {
            Console.WriteLine("正在接收客户端连接... ...");
            Socket clientSocket = serverSocket.EndAccept(ar);

            Console.WriteLine("接收到一条客户端连接" + ar.ToString());
            Client client = new Client(clientSocket, this);

            clientList.Add(client);
            //该客户端socket开启监听客户端消息
            client.Start();
            //继续接收下一个客户端连接
            serverSocket.BeginAccept(AcceptCallBack, null);
        }
示例#9
0
        /// <summary>
        /// Callback for Write operation
        /// </summary>
        private void SendCallback(IAsyncResult result)
        {
            if (this._isConnected)
            {
                if (result.IsCompleted)
                {
                    Int32 sentbytes = 0;
                    try
                    {
                        sentbytes = this.mySocket.EndSend(result); //Ends Sending initiated by BeginSend(); Returns Bytes that have been sent
                    }
                    catch (ArgumentNullException ex)
                    {
                        //asyncResult is null.
                    }
                    catch (ArgumentException ex)
                    {
                        //asyncResult was not returned by a call to the BeginSend method.
                    }
                    catch (SocketException ex)
                    {
                        //An error occurred when attempting to access the socket. See the Remarks section for more information.
                    }
                    catch (ObjectDisposedException ex)
                    {
                        //The Socket has been closed.
                    }
                    catch (InvalidOperationException ex)
                    {
                        //EndSend was previously called for the asynchronous send.
                    }

                    if (sentbytes < this.mySocket.SendBufferSize)
                    {//Less Bytes than Buffer were sent... seems something ist missing
                    }

                    //Datentransfer abgeschlossen
                    if (this.DataSent != null)
                    {
                        this.DataSent(
                            this,
                            new Co0nUtilZ.ProgressEventArgs(
                                100,
                                result.ToString() + " (Bytes=" + sentbytes + ")"
                                )
                            );
                    }
                }
            }
        }
示例#10
0
        private void callBack(IAsyncResult ar)
        {
            lock (locker) {
                var ie = (IEnumerator)ar.AsyncState;
                var th = GetCothread(ie);
                if (th.AsyncResult != ar)
                {
                    Log("****[Hub.callBack]" + ar.ToString() + "******");
                    return;
                }

                th.AsyncResult = null;
                addCothread(ie);
            }
        }
示例#11
0
            public void Add(IAsyncResult asyncResult, IDisposable disposable)
            {
                if (asyncResult == null)
                {
                    throw new ArgumentNullException(asyncResult.ToString());
                }
                if (disposable == null)
                {
                    throw new ArgumentNullException(disposable.ToString());
                }

                lock (_syncRoot)
                {
                    _items.Enqueue(new TimeoutItem(_stopwatch.ElapsedTicks + _timeout, asyncResult, disposable));
                }
            }
        private void onfinished(IAsyncResult ar)
        {
            if (ar.IsCompleted == false)
            {
                ActiveLogger.LogMessage("Thread finished with errors " + ar.ToString(), LogLevel.RecoverableError);
                return;
            }

            ITask task = ar.AsyncState as ITask;

            System.Diagnostics.Debug.Assert(task != null);

            lock (finished)
            {
                finished.Add(task);
            }
        }
示例#13
0
        // once connected. we start to read data and ping.
        private void _onConnected(IAsyncResult result)
        {
            Debug.Log("_onConnected " + _tcpClient.Connected.ToString() + "  " + result.ToString());
            if (true == _tcpClient.Connected)
            {
                Console.WriteLine("{0} connect to server is successful.", _tcpClient.Client.ToString());
            }
            else
            {
                Console.WriteLine("Connecting error and failed.");
                WorldPack Packet = new WorldPack(Opcodes.SMSG_CONNECT_FAILED, 0);
                if (null != _packHandler)
                {
                    // push into a packet array.
                    addEvent(Packet);
                }
                _tcpClient.Close();
                _tcpClient = null;
                return;
            }

            // init stuff.
            _rpos = _wpos = 0;

            Debug.Log("_onConnected read first ");

            _netStream = new NetworkStream(_tcpClient.Client);
            _netStream.BeginRead(
                _read,
                (int)_wpos,
                (int)(_read.Length - _wpos),
                new AsyncCallback(_onRead),
                null);
            // 将下次收发的数据放到 _read _wpos的位置。并调用 onRead处理buffer。
            // init sending pings.
            // SendPing();

            Debug.Log("_onConnected end ");
        }
示例#14
0
        private void Callback_Connect(IAsyncResult result)
        {
            Debug.Log(LogHeader.Function + "result:" + result.ToString());
            try {
                _socket = (Socket)result.AsyncState;
                _socket.EndConnect(result);
                _socket.ReceiveBufferSize = Gamnet.Buffer.BUFFER_SIZE;
                _socket.SendBufferSize    = Gamnet.Buffer.BUFFER_SIZE;
                //_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000);
                //_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000);
                //_timer.Enabled = false;
                _timer.Stop();

                Receive();

                _state           = ConnectionState.Connected;
                _disconnectState = DisconnectState.Invalid;

                Send_Connect_Req();

                _timer           = new System.Timers.Timer();
                _timer.Interval  = heartbeat_time;
                _timer.AutoReset = true;
                _timer.Elapsed  += delegate {
                    if (false == _timer.Enabled)
                    {
                        return;
                    }
                    Send_HeartBeat_Req();
                };
                _timer.Start();
            }
            catch (System.Exception e) {
                Debug.LogError("[Session.Callback_Connect] exception:" + e.ToString());
                Error(new Gamnet.Exception(ErrorCode.ConnectFailError, e.ToString()));
                Disconnect();
            }
        }
示例#15
0
 private static void _shrinkFile(SqlConnection Connection, string dbName, FileList <string> files, int ShrinkTo = 1)
 {
     foreach (string fileName in files)
     {
         string query = $" USE [{dbName}]" +
                        $" DBCC SHRINKFILE (N'{fileName}' , {ShrinkTo})";
         Splash splash             = Splash.ShowSplash($"Shrinking {fileName}");
         var    shrinkerConnection = new SqlConnection(Connection.ConnectionString);
         shrinkerConnection.Open();
         IAsyncResult shrinker = Helpers.ExecuteNonQuery(query, shrinkerConnection, 0);
         int          sid      = -1;
         bool         repeat   = true;
         do
         {
             Thread.Sleep(100);
             try {
                 sid =
                     int.Parse(Helpers.ExecuteScalar(
                                   "SELECT session_id from sys.dm_exec_requests WHERE command like '%DbccFilesCompact%'",
                                   Connection));
                 repeat = false;
             }
             catch (Exception e) {
                 Console.WriteLine(e);
             }
         } while (!shrinker.IsCompleted & repeat);
         while (!shrinker.IsCompleted)
         {
             Debug.WriteLine(shrinker.ToString());
             splash.Status = "Percent complete: "
                             + Helpers.ExecuteScalar($"SELECT percent_complete from sys.dm_exec_requests WHERE session_id = {sid}", Connection) + $" Session ID = {sid}";
             Thread.Sleep(1000);
         }
         shrinkerConnection.Close();
         splash.CloseSplash();
     }
 }
        void HandleRead(IAsyncResult ar)
        {
            lock (comlock)
            {
                int bytes;
                try
                {
                    bytes = Pipe.EndRead(ar);
                    if (bytes == 0)
                    {
                        Debug.Print(ar.ToString());
                        Debug.Print(ar.CompletedSynchronously.ToString());
                        Debug.Print(ar.IsCompleted.ToString());
                        onFailure("No bytes to read, pipe closed");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(string.Format("End Read Failed {0}", e.ToString()));
                    onFailure("End read threw exception " + e.ToString());
                    return;
                }

                try
                {
                    processData(bytes);

                    try {
                        Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                    }
                    catch {
                        onFailure("Pipe broken");
                        return;
                    }
                }
                catch (EndOfStreamException)
                {
                    if (bufferreadpos == buffersize)
                    {
                        buffersize = buffersize * 2;
                        byte[] newbuffer = new byte[buffersize];
                        buffer.CopyTo(newbuffer, 0);
                        buffer = newbuffer;
                    }
                    try
                    {
                        Debug.Print("new read " + bufferreadpos.ToString() + " " + (buffersize - bufferreadpos).ToString());
                        if (!Pipe.CanRead)
                        {
                            Debug.Print("For some reason I can't read from this pipe.  Ideas?");
                        }
                        if (!Pipe.IsConnected) {
                            onFailure("Pipe has gone away");
                            return;
                        }
                        try {
                            Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                        }
                        catch {
                            onFailure("Pipe broken");
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Print("Communicator found too little to read : " + buffersize.ToString() + " " + bufferreadpos.ToString() + " " + e.ToString());
                        onFailure("Insufficient data to read");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print("Communicator failure :" + e.ToString());
                    onFailure("Handle read comms failure : " + e.ToString());
                    return;
                }
            }
        }
示例#17
0
        public void OnRecieve(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);
                MessageBox.Show(clientSocket.ToString() + "\n" + clientSocket.SocketType.ToString() + "\n" + ar.AsyncState.ToString() + "\n" + ar.ToString());

                Data recMsg = new Data(byteData);

                Data sendMsg = new Data();

                byte[] msg;

                sendMsg.cmd = recMsg.cmd;
                sendMsg.user = recMsg.user;

                switch (recMsg.cmd)
                {
                    case Command.Login:
                        ClientInfo clientInfo = new ClientInfo();
                        clientInfo.socket = clientSocket;
                        clientInfo.user = recMsg.user;

                        clientList.Add(clientInfo);

                        sendMsg.Msg = ">> " + recMsg.user + " has joined the server \\o/";
                        break;

                    case Command.Logout:

                        int id = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.socket == clientSocket)
                            {
                                clientList.RemoveAt(id);
                                break;
                            }
                            ++id;
                        }
                        clientSocket.Close();
                        sendMsg.Msg = ">> " + recMsg.user + " just left the server :c ";
                        break;

                    case Command.Message:
                        sendMsg.Msg = recMsg.user + ": " + recMsg.Msg;
                        break;

                    case Command.List:
                        sendMsg.cmd = Command.List;
                        sendMsg.user = null;
                        sendMsg.Msg = null;

                        foreach (ClientInfo client in clientList)
                        {
                            sendMsg.Msg += client.user + "*";
                        }

                        msg = sendMsg.toByte();

                        clientSocket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);
                        break;
                }
                if (sendMsg.cmd != Command.List)
                {
                    msg = sendMsg.toByte();
                    foreach (ClientInfo c in clientList)
                    {
                        if (c.socket != clientSocket || sendMsg.cmd != Command.Login)
                        {
                            c.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(OnSend), c.socket);
                        }
                    }

                    tBox_log.Text += sendMsg.Msg + "\r\n";
                }

                if (recMsg.cmd != Command.Logout)
                {
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnRecieve), clientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#18
0
 public string EndSessionTwoWayMethod(IAsyncResult r)
 {
     Log.Trace("EndSessionTwoWayMethod: " + r.ToString());
     return(myAsyncSessionTwoWayDelegate.EndInvoke(r));
 }
示例#19
0
        //event 3, do receive stuff for clients.
        // use tcpClients snync reading methods, read them into circular buffer, and make worldpack.
        // Callback function when receive byte data,Using tcpClient start read sync fucntion.
        private void _onRead(IAsyncResult result)
        {
            Debug.Log("_onRead " + result.ToString());
            // check if we have been gc or closed.
            if (!connected() || null == _netStream)
            {
                return;
            }

            int readByteThisTime = _netStream.EndRead(result);

            if (readByteThisTime <= 0)
            {
                Debug.LogError("NetErrorCode.NET_RECV_ERROR");
                Console.WriteLine("NetErrorCode.NET_RECV_ERROR");
                Disconnect();
                // TryToConnect();
                return;
            }
            Debug.Log("_onRead Receive beytes " + readByteThisTime.ToString());
            //Console.WriteLine("Receive beytes {0}",readByteThisTime);

            _wpos += (UInt16)readByteThisTime;
            // _wpos 为当前系统向_read中数据写到的长度。指向_read中数据的结尾处。
            // _rpos指向当前读数据开始的位置,只有在成功读出一个包的时候才改变它。
            // 缓存中当前处理实际数据大小为 _wpos-_rpos.
            // 循环处理多个包之后,缓存中的数据不足以一个包的时候,做自拷贝动作。
            // :将 _rpos --> _wpos的数据拷贝到_read开头。
            // _wpos and _rpos  all --rpos;

            while (true)
            {
                Debug.Log("_onRead(While)1" + _wpos.ToString() + "  " + _rpos.ToString());
                Debug.Log("_onRead(While)2 _read=" + _read.ToString());
                for (int i = 0; i < 5; i++)
                {
                    Debug.Log("_onRead(While) _read:" + i.ToString() + "->" + _read[i].ToString());
                }
                Debug.Log("_onRead(While)3");
                int size = _wpos - _rpos;
                System.Diagnostics.Debug.Assert(size >= 0);
                if (size < GC_NET_HEAD_LENGTH)
                {
                    break;                              /* no head in the apcket, let's wait.*/
                }
                Debug.Log("_onRead(While)4");
                int packetSize = HandleGcPack(_read, size, _rpos);
                if (packetSize < 0)
                {
                    break;                  /*we have a fragmented apcket. wait fot the complete one before proceeding*/
                }
                _rpos += (UInt16)(packetSize + GC_NET_HEAD_LENGTH);
                Debug.Log("_onRead(While)5");
            }

            // copy the left data to the top.
            if (_wpos > _rpos)
            {
                Array.Copy(_read, _rpos, _read, 0, _wpos - _rpos);
            }

            _wpos -= _rpos; // _wpos == _read.getLenth(0);
            _rpos  = 0;
            Debug.Log("_onRead(While)  end");
            System.Diagnostics.Debug.Assert(_netStream != null);
            if (true == _tcpClient.Connected)
            {
                Debug.Log("_onRead to  _onRead");

                _netStream.BeginRead(
                    _read,
                    (int)_wpos,
                    (int)(_read.Length - _wpos),
                    new AsyncCallback(_onRead),
                    null);

                Debug.Log("_onRead to  _onRead2");
            }

            // do a mess packets read to test this code.
        }
示例#20
0
        void HandleRead(IAsyncResult ar)
        {
            lock (comlock)
            {
                int bytes;
                try
                {
                    bytes = Pipe.EndRead(ar);
                    if (bytes == 0)
                    {
                        Debug.Print(ar.ToString());
                        Debug.Print(ar.CompletedSynchronously.ToString());
                        Debug.Print(ar.IsCompleted.ToString());
                        onFailure("No bytes to read, pipe closed");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(string.Format("End Read Failed {0}", e.ToString()));
                    onFailure("End read threw exception " + e.ToString());
                    return;
                }

                try
                {
                    processData(bytes);

                    try {
                        Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                    }
                    catch {
                        onFailure("Pipe broken");
                        return;
                    }
                }
                catch (EndOfStreamException)
                {
                    if (bufferreadpos == buffersize)
                    {
                        buffersize = buffersize * 2;
                        byte[] newbuffer = new byte[buffersize];
                        buffer.CopyTo(newbuffer, 0);
                        buffer = newbuffer;
                    }
                    try
                    {
                        Debug.Print("new read " + bufferreadpos.ToString() + " " + (buffersize - bufferreadpos).ToString());
                        if (!Pipe.CanRead)
                        {
                            Debug.Print("For some reason I can't read from this pipe.  Ideas?");
                        }
                        if (!Pipe.IsConnected)
                        {
                            onFailure("Pipe has gone away");
                            return;
                        }
                        try {
                            Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                        }
                        catch {
                            onFailure("Pipe broken");
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Print("Communicator found too little to read : " + buffersize.ToString() + " " + bufferreadpos.ToString() + " " + e.ToString());
                        onFailure("Insufficient data to read");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print("Communicator failure :" + e.ToString());
                    onFailure("Handle read comms failure : " + e.ToString());
                    return;
                }
            }
        }
示例#21
0
 public void EndOneWayMethod(IAsyncResult r)
 {
     Log.Trace("EndOneWayMethod: " + r.ToString());
     myAsyncOneWayDelegate.EndInvoke(r);
 }       
示例#22
0
 private void ReadCallback(IAsyncResult result)
 {
     result.ToString();
 }
示例#23
0
 //发送成功回调
 private void sendCallback(IAsyncResult asyncSend)
 {
     Console.WriteLine("Send msg success" + asyncSend.ToString());
 }
示例#24
0
 public void EndOneWayMethod(IAsyncResult r)
 {
     Log.Trace("EndOneWayMethod: " + r.ToString());
     myAsyncOneWayDelegate.EndInvoke(r);
 }
示例#25
0
 public string EndSessionTwoWayMethod(IAsyncResult r)
 {
     Log.Trace("EndSessionTwoWayMethod: " + r.ToString());
     return (myAsyncSessionTwoWayDelegate.EndInvoke(r));
 }
示例#26
0
        //call backs also run in the same thread in which begin invoke runs on.
        static void callBack(IAsyncResult result)
        {
            string res = result.ToString();

            Console.WriteLine("[{0}] Call back method res ={1}", Thread.CurrentThread.ManagedThreadId, res);
        }
示例#27
0
文件: Socket.cs 项目: mengtest/u3dmmo
        //event 3, do receive stuff for clients.
        // use tcpClients snync reading methods, read them into circular buffer, and make worldpack.
        // Callback function when receive byte data,Using tcpClient start read sync fucntion.
        private void _onRead(IAsyncResult result)
        {
            Debug.Log("_onRead " + result.ToString());
            // check if we have been gc or closed.
            if (!connected() || null == _netStream)
            {
                return;
            }

            int readByteThisTime = _netStream.EndRead(result);

            if (readByteThisTime <= 0)
            {
                Debug.LogError("NetErrorCode.NET_RECV_ERROR");
                Console.WriteLine("NetErrorCode.NET_RECV_ERROR");
                Disconnect();
                // TryToConnect();
                return;
            }
            Debug.Log("_onRead Receive beytes " + readByteThisTime.ToString());
            //Console.WriteLine("Receive beytes {0}",readByteThisTime);

            _wpos += (UInt16)readByteThisTime;
            // _wpos 为当前系统向_read中数据写到的长度。指向_read中数据的结尾处。
            // _rpos指向当前读数据开始的位置,只有在成功读出一个包的时候才改变它。
            // 缓存中当前处理实际数据大小为 _wpos-_rpos.
            // 循环处理多个包之后,缓存中的数据不足以一个包的时候,做自拷贝动作。
            // :将 _rpos --> _wpos的数据拷贝到_read开头。
            // _wpos and _rpos  all --rpos;

            while (true)
            {
                Debug.Log("_onRead(While)" + _wpos.ToString() + "  " + _rpos.ToString());
                Debug.Log("_onRead(While) _read=" + _read.ToString());
                for (int i = 0; i < 11; i++)
                {
                    Debug.Log("_onRead(While) _read:" + i.ToString() + "->" + _read[i].ToString());
                }

                int size = _wpos - _rpos;
                System.Diagnostics.Debug.Assert(size >= 0);
                if (size < 6)
                {
                    break;             /* no head in the apcket, let's wait.*/
                }

                // head: size(u16)+code(u32)
                UInt16 packetSize = BitConverter.ToUInt16(_read, (int)_rpos);
                if (packetSize < 4)
                {
                    Debug.LogError("packetSize<4!!"); break;
                }

                packetSize = (UInt16)(packetSize - 4);
                if (size < packetSize + S2C_PACK_HEAD_SIZE)
                {
                    break;                                          /*we have a fragmented apcket. wait fot the complete one before proceeding*/
                }
                Opcodes code = (Opcodes)BitConverter.ToUInt32(_read, (int)_rpos + MESSAGEHEAD_SIZE_LENGTH);

                WorldPack Packet = new WorldPack(code, packetSize);
                Packet.append(_read, _rpos + S2C_PACK_HEAD_SIZE, packetSize); // 将缓存中,从当前_rpos + 包头的数据给WorldPack.

                // 纪录发包either.
                // LogPacketPrintf(mSize, static_cast<uint16>(mOpcode), mSize ? Packet->contents() : NULL, 0, 0);
                _rpos += (UInt16)(packetSize + S2C_PACK_HEAD_SIZE);

                if (Packet.opcode() == Opcodes.SMSG_PONG)
                {
                    _handlePong(Packet);
                }
                else if (null != _packHandler)
                {
                    // push into a packet array.
                    addEvent(Packet);
                }
            }

            // copy the left data to the top.
            if (_wpos > _rpos)
            {
                Array.Copy(_read, _rpos, _read, 0, _wpos - _rpos);
            }

            _wpos -= _rpos; // _wpos == _read.getLenth(0);
            _rpos  = 0;
            Debug.Log("_onRead(While)  end");
            System.Diagnostics.Debug.Assert(_netStream != null);
            if (true == _tcpClient.Connected)
            {
                Debug.Log("_onRead to  _onRead");

                _netStream.BeginRead(
                    _read,
                    (int)_wpos,
                    (int)(_read.Length - _wpos),
                    new AsyncCallback(_onRead),
                    null);

                Debug.Log("_onRead to  _onRead2");
            }

            // do a mess packets read to test this code.
        }
        private void onfinished(IAsyncResult ar)
        {
            if (ar.IsCompleted == false)
            {
                ActiveLogger.LogMessage("Thread finished with errors " + ar.ToString(), LogLevel.RecoverableError);
                return;
            }

            ITask task = ar.AsyncState as ITask;
            System.Diagnostics.Debug.Assert(task != null);

            lock (finished)
            {
                finished.Add(task);
            }
        }
示例#29
0
        private void CameraMovementCallback(IAsyncResult ar)
        {
            logger.Info("Camera movement {0}", ar.ToString());

            try
            {
                // Restart receive
                _udpClientForCameraMovement.BeginReceive(new AsyncCallback(CameraMovementCallback), null);
                _actionDetectedCallback();
            }
            catch (Exception excp)
            {
                logger.Error("Exception in MainWindow::CameraMovementCallback2 {0}", excp.Message);
            }
        }
示例#30
0
 private void FinishWebRequest(IAsyncResult result)
 {
     Host.Logger.WriteLine(result.ToString());
 }