예제 #1
0
        //private object m_LockCommunication = new int();
        private void _listener(object state)
        {
            int buflen = 0;

            byte[] buf = new byte[8192];
            //C5.LinkedList<byte> totalBuf = new C5.LinkedList<byte>();
            DefLib.Util.ArrayBuilder <byte> totalBuf = new DefLib.Util.ArrayBuilder <byte>();

            byte[] rest = null;

            try
            {
                //NetworkStream stream = m_Client.GetStream();

                m_ListenerClearEvent.Reset();

                while (Interlocked.Read(ref m_Run) == 1)
                {
                    if (Interlocked.Read(ref m_Run) == 0)
                    {
                        break;
                    }

                    try
                    {
                        totalBuf.Clear();

                        /// 读取Socket缓冲区
                        ///
                        while (true)
                        {
                            lock (m_Client)
                            {
                                if (!m_Client.Poll(100, SelectMode.SelectRead))
                                {
                                    break;
                                }
                            }

                            if (Interlocked.Read(ref m_Run) == 0)
                            {
                                totalBuf.Clear();
                                break;
                            }

                            buflen = 0;
                            lock (m_Client)
                            {
                                if (m_Client.Connected)
                                {
                                    buflen = m_Client.Receive(buf, buf.Length, SocketFlags.None);
                                }
                            }

                            if (buflen > 0)
                            {
                                totalBuf.Append(buf, buflen);
                                //for (int i = 0; i < buflen; ++i)
                                //    totalBuf.Add(buf[i]);
                            }
                            else
                            {
                                throw new CommException("读到零字节数据.");
                            }

                            if (totalBuf.Length > 102400)
                            {
                                break;
                            }
                        }

                        if (totalBuf.Length > 0)
                        {
                            if (rest != null)
                            {
                                totalBuf.Insert(0, rest, rest.Length);
                                //totalBuf.InsertAll(0, rest);
                                rest = null;
                            }

                            if (m_Extractor == null)
                            {
                                totalBuf.Clear();
                                continue;
                            }

                            //SendLog(totalBuf.Count + " Bytes recved: " + DumpByte2Str(totalBuf.ToArray()));

                            // 解析收到的数据
                            List <ICommunicationMessage> messages = m_Extractor.extractMessages(totalBuf.ToArray(), ref rest);

                            // 派发给侦听者
                            if (messages.Count > 0)
                            {
                                List <ICommunicationMessage> queue = new List <ICommunicationMessage>();
                                foreach (ICommunicationMessage command in messages)
                                {
                                    try
                                    {
                                        command.SetValue("ClientID", m_ClientID);

                                        if (command.TK_CommandType == Constants.TK_CommandType.KEEPALIVE)
                                        {
                                            command.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                                            command.SetValue("RESPONSE_TO", command.SeqID);
                                            command.SetValue("RESULT", "OK");
                                            command.SeqID = CommandProcessor.AllocateID();

                                            enqueueMessage(command);
                                            continue;
                                        }

                                        queue.Add(command);
                                    } // end try
                                    catch
                                    { }
                                } // end for

                                if (queue.Count > 0)
                                {
                                    m_ParentCommer.FilterResponse(queue);
                                }

                                if (queue.Count > 0)
                                {
                                    CommandProcessor.instance().DispatchCommands(queue);
                                }
                            } // end if messages.Count
                        }
                    }
                    catch (CommException commex)
                    {
                        throw new CommException(commex.ToString());
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("通讯异常:\n" + ex.ToString());
                    }

                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //SendLog(m_ClientInfo.ToString() + "侦听线程异常退出:\n" + ex.ToString());
                    m_ListenerClearEvent.Set();
                }
                catch { }

                try
                {
                    InvokeConnectionBroken(this, ex.Message);
                    return;
                }
                catch { }
            }
            finally
            {
                try
                {
                    m_ListenerClearEvent.Set();
                }
                catch { }
            }
        }
예제 #2
0
        private void _recvCallback(IAsyncResult ar)
        {
            SocketError err_code;

            try
            {
                int buflen = m_Client.EndReceive(ar, out err_code);
                m_RecvDone.Set();

                if (err_code != SocketError.Success)
                {
                    InvokeConnectionBroken(this, new SocketException((int)err_code).Message);
                    return;
                }

                if (buflen == 0)
                {
                    InvokeConnectionBroken(this, "收到零字节数据.");
                    return;
                }

                totalBuf.Clear();
                totalBuf.Append(buf, buflen);
                if (rest != null)
                {
                    totalBuf.Insert(0, rest, rest.Length);
                    rest = null;
                }

                if (m_Extractor == null)
                {
                    totalBuf.Clear();
                    return;
                }

                //SendLog(totalBuf.Count + " Bytes recved: " + DumpByte2Str(totalBuf.ToArray()));

                // 解析收到的数据
                List <ICommunicationMessage> messages = m_Extractor.extractMessages(totalBuf.ToArray(), ref rest);

                // 派发给侦听者
                if (messages.Count > 0)
                {
                    ++m_RecvCount;
                    //DefLib.Util.Logger.Instance().SendLog("AsyncComm", "Received[" + ClientID + "]: " + m_RecvCount);

                    List <ICommunicationMessage> queue = new List <ICommunicationMessage>();
                    foreach (ICommunicationMessage command in messages)
                    {
                        try
                        {
                            command.SetValue("ClientID", m_ClientID);

                            if (command.TK_CommandType == Constants.TK_CommandType.KEEPALIVE)
                            {
                                command.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                                command.SetValue("RESPONSE_TO", command.SeqID);
                                command.SetValue("RESULT", "OK");
                                command.SeqID = CommandProcessor.AllocateID();

                                enqueueMessage(command);
                                continue;
                            }

                            queue.Add(command);
                        } // end try
                        catch
                        { }
                    } // end for

                    if (queue.Count > 0)
                    {
                        m_ParentCommer.FilterResponse(queue);
                    }

                    if (queue.Count > 0)
                    {
                        CommandProcessor.instance().DispatchCommands(queue);
                    }
                } // end if messages.Count

                if (Interlocked.Read(ref m_Run) != 0)
                {
                    _recvAsync();
                }
            }
            catch (Exception ex)
            {
                m_RecvDone.Set();
                InvokeConnectionBroken(this, ex.ToString());
            }
            finally
            {
            }
        }