Esempio n. 1
0
        /// <summary>
        /// Send synchronous message
        /// </summary>
        /// <param name="evt">Event</param>
        /// <param name="msg">message</param>
        /// <param name="milliseconds">time out</param>
        /// <returns>response object. If no reponse from server, return null</returns>
        public object SendSyncMessage(short evt, object msg)
        {
            if (_ClientStream == null)
            {
                Connect();
            }

            try
            {
                lock (this)
                {
                    TcpCacheStream tcpStream = new TcpCacheStream(_ClientStream);

                    object result = null;

                    MessageHead head = new MessageHead(evt);

                    if (msg == null)
                    {
                        head.Flag |= MessageFlag.NullData;
                    }

                    //Send event
                    byte[] sendBuf = BitConverter.GetBytes(head.Event);
                    tcpStream.Write(sendBuf, 0, sendBuf.Length);

                    if (msg != null)
                    {
                        //Send Flag

                        if (msg is string)
                        {
                            head.Flag |= MessageFlag.IsString;
                            sendBuf    = BitConverter.GetBytes((short)head.Flag);
                            tcpStream.Write(sendBuf, 0, sendBuf.Length);

                            byte[] buf = Encoding.UTF8.GetBytes((msg as string));

                            for (int i = 0; i < buf.Length; i++)
                            {
                                if (buf[i] == 0)
                                {
                                    buf[i] = 0x20;
                                }
                            }

                            tcpStream.Write(buf, 0, buf.Length);
                            tcpStream.WriteByte(0);
                        }
                        else
                        {
                            sendBuf = BitConverter.GetBytes((short)head.Flag);
                            tcpStream.Write(sendBuf, 0, sendBuf.Length);
                            IFormatter formatter = new BinaryFormatter();
                            formatter.Serialize(tcpStream, msg);
                        }
                    }
                    else
                    {
                        //Send Flag
                        sendBuf = BitConverter.GetBytes((short)head.Flag);
                        tcpStream.Write(sendBuf, 0, sendBuf.Length);
                    }

                    tcpStream.Flush();

                    tcpStream = new TcpCacheStream(_ClientStream);

                    //Recevie data

                    byte[] revBuf = new byte[4];
                    int    offset = 0;

                    while (offset < 4)
                    {
                        int len = tcpStream.Read(revBuf, offset, 4 - offset);

                        if (len == 0)
                        {
                            throw new Exception("Tcp stream closed!");
                        }


                        offset += len;
                    }

                    head.Event = BitConverter.ToInt16(revBuf, 0);
                    head.Flag  = (MessageFlag)BitConverter.ToInt16(revBuf, 2);

                    if ((head.Flag & MessageFlag.NullData) == 0)
                    {
                        if ((head.Flag & MessageFlag.CustomSerialization) != 0)
                        {
                            if (RequireCustomSerialization != null)
                            {
                                Hubble.Framework.Serialization.IMySerialization mySerializer =
                                    RequireCustomSerialization(head.Event, null);

                                if (mySerializer == null)
                                {
                                    throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
                                                                      head.Event));
                                }

                                result = mySerializer.Deserialize(tcpStream, mySerializer.Version);
                            }
                            else
                            {
                                throw new Exception("RequireCustomSerialization of TcpClient is null!");
                            }
                        }
                        else if ((head.Flag & MessageFlag.IsString) == 0)
                        {
                            IFormatter formatter = new BinaryFormatter();
                            result = formatter.Deserialize(tcpStream);
                        }
                        else
                        {
                            MemoryStream m = new MemoryStream();

                            byte[] buf = new byte[1024];

                            int len = 0;
                            do
                            {
                                len = tcpStream.Read(buf, 0, buf.Length);
                                if (buf[len - 1] == 0)
                                {
                                    m.Write(buf, 0, len - 1);
                                    break;
                                }
                                else
                                {
                                    m.Write(buf, 0, len);
                                }
                            } while (true);

                            m.Position = 0;

                            using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                            {
                                result = sr.ReadToEnd();
                            }

                            if ((head.Flag & MessageFlag.IsException) != 0)
                            {
                                string[] strs = Hubble.Framework.Text.Regx.Split(result as string, "innerStackTrace:");

                                result = new InnerServerException(strs[0], strs[1]);
                            }
                        }

                        if (result is InnerServerException)
                        {
                            throw new ServerException(result as InnerServerException);
                        }
                        else if (result is Exception)
                        {
                            throw result as Exception;
                        }
                    }

                    return(result);
                }
            }
            catch (System.IO.IOException ioEx)
            {
                Close();
                throw ioEx;
            }
        }
Esempio n. 2
0
        private void HandleClientComm(object pcb)
        {
            PCB p = (PCB)pcb;

            System.Net.Sockets.TcpClient tcpClient = p.Client;
            object lockObj = new object();

            try
            {
                try
                {
                    OnConnectEstablishEvent(new ConnectEstablishEventArgs(p.ThreadId));
                }
                catch (Exception e)
                {
                    OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
                }

                System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();

                TcpCacheStream tcpStream = new TcpCacheStream(clientStream);

                while (true)
                {
                    MessageHead msgHead = new MessageHead();

                    try
                    {
                        bool   disconnected = false;
                        object msg          = null;

                        //Recevie data
                        //Stream tcpStream = clientStream;

                        byte[] revBuf = new byte[4];
                        int    offset = 0;

                        while (offset < 4)
                        {
                            int len;

                            try
                            {
                                len = tcpStream.Read(revBuf, offset, 4 - offset);
                            }
                            catch
                            {
                                disconnected = true;
                                break;
                            }

                            if (len == 0)
                            {
                                //Disconnect
                                disconnected = true;
                                break;
                            }

                            offset += len;
                        }

                        if (disconnected)
                        {
                            break;
                        }

                        msgHead.Event = BitConverter.ToInt16(revBuf, 0);
                        msgHead.Flag  = (MessageFlag)BitConverter.ToInt16(revBuf, 2);

                        bool isAsync = (msgHead.Flag & MessageFlag.ASyncMessage) != 0;
                        int  classId = -1;

                        if (isAsync)
                        {
                            if (!Hubble.Framework.IO.Stream.ReadToBuf(tcpStream, revBuf, 0, 4))
                            {
                                disconnected = true;
                                break;
                            }
                            else
                            {
                                classId = BitConverter.ToInt32(revBuf, 0);
                            }
                        }


                        if ((msgHead.Flag & MessageFlag.NullData) == 0)
                        {
                            if ((msgHead.Flag & MessageFlag.CustomSerialization) != 0)
                            {
                                if (RequireCustomSerialization != null)
                                {
                                    Hubble.Framework.Serialization.IMySerialization mySerializer =
                                        RequireCustomSerialization(msgHead.Event, null);

                                    if (mySerializer == null)
                                    {
                                        throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
                                                                          msgHead.Event));
                                    }

                                    msg = mySerializer.Deserialize(tcpStream, mySerializer.Version);
                                }
                                else
                                {
                                    throw new Exception("RequireCustomSerialization of TcpClient is null!");
                                }
                            }
                            else if ((msgHead.Flag & MessageFlag.IsString) == 0)
                            {
                                IFormatter formatter = new BinaryFormatter();
                                msg = formatter.Deserialize(tcpStream);
                            }
                            else
                            {
                                if ((msgHead.Flag & MessageFlag.IsString) != 0 &&
                                    (msgHead.Flag & MessageFlag.ASyncMessage) != 0)
                                {
                                    MemoryStream m = new MemoryStream();

                                    byte b = (byte)tcpStream.ReadByte();
                                    while (b != 0)
                                    {
                                        m.WriteByte(b);
                                        b = (byte)tcpStream.ReadByte();
                                    }

                                    m.Position = 0;

                                    using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                                    {
                                        msg = sr.ReadToEnd();
                                    }
                                }
                                else
                                {
                                    MemoryStream m = new MemoryStream();

                                    byte[] buf = new byte[1024];

                                    int len = 0;

                                    do
                                    {
                                        len = tcpStream.Read(buf, 0, buf.Length);
                                        if (buf[len - 1] == 0)
                                        {
                                            m.Write(buf, 0, len - 1);
                                            break;
                                        }
                                        else
                                        {
                                            m.Write(buf, 0, len);
                                        }
                                    } while (true);

                                    m.Position = 0;

                                    using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                                    {
                                        msg = sr.ReadToEnd();
                                    }
                                }
                            }
                        }

                        MessageReceiveEventArgs receiveEvent = new MessageReceiveEventArgs(
                            this, msgHead, msg, p.ThreadId, classId, tcpClient,
                            clientStream, lockObj);

                        Hubble.Framework.Serialization.IMySerialization customSerializer = null;

                        try
                        {
                            OnMessageReceiveEvent(receiveEvent);
                            customSerializer = receiveEvent.CustomSerializtion;
                        }
                        catch (System.Threading.ThreadAbortException)
                        {
                            receiveEvent.ReturnMsg = new System.Threading.ThreadInterruptedException("Thread abort. Maybe execute select too long. Please check the error log.");
                            System.Threading.Thread.ResetAbort();
                        }
                        catch (Exception e)
                        {
                            receiveEvent.ReturnMsg = e;
                        }

                        if (!isAsync)
                        {
                            ReturnMessage(lockObj, tcpClient, msgHead, receiveEvent.ReturnMsg, customSerializer);
                        }
                    }
                    catch (Exception innerException)
                    {
                        try
                        {
                            OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(msgHead, innerException));
                        }
                        catch
                        {
                        }

                        if (tcpClient.Connected)
                        {
                            tcpClient.Close();
                        }

                        throw innerException;
                    }
                }

                tcpClient.Close();
            }
            catch (Exception e)
            {
                OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
            }
            finally
            {
                try
                {
                    OnDisconnectEvent(new DisconnectEventArgs(p.ThreadId));
                }
                catch (Exception e)
                {
                    OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
                }

                RetPCB(p);
            }
        }
Esempio n. 3
0
        private void AsyncMessageRecv()
        {
            TcpCacheStream tcpStream = new TcpCacheStream(_ClientStream);

            while (true)
            {
                try
                {
                    object result;

                    //Recevie data

                    byte[] revBuf = new byte[8];
                    int    offset = 0;

                    while (offset < 8)
                    {
                        int len = tcpStream.Read(revBuf, offset, 8 - offset);

                        if (len == 0)
                        {
                            throw new Exception("Tcp stream closed!");
                        }

                        offset += len;
                    }

                    MessageHead head = new MessageHead();

                    head.Event = BitConverter.ToInt16(revBuf, 0);
                    head.Flag  = (MessageFlag)BitConverter.ToInt16(revBuf, 2);

                    int classId = BitConverter.ToInt32(revBuf, 4);

                    if ((head.Flag & MessageFlag.NullData) == 0)
                    {
                        if ((head.Flag & MessageFlag.CustomSerialization) != 0)
                        {
                            if (RequireCustomSerialization != null)
                            {
                                Hubble.Framework.Serialization.IMySerialization mySerializer =
                                    RequireCustomSerialization(head.Event, null);

                                if (mySerializer == null)
                                {
                                    throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
                                                                      head.Event));
                                }

                                result = mySerializer.Deserialize(tcpStream, mySerializer.Version);
                            }
                            else
                            {
                                throw new Exception("RequireCustomSerialization of TcpClient is null!");
                            }
                        }
                        else if ((head.Flag & MessageFlag.IsString) == 0)
                        {
                            IFormatter formatter = new BinaryFormatter();
                            result = formatter.Deserialize(tcpStream);
                        }
                        else
                        {
                            MemoryStream m = new MemoryStream();

                            byte b = (byte)tcpStream.ReadByte();
                            while (b != 0)
                            {
                                m.WriteByte(b);
                                b = (byte)tcpStream.ReadByte();
                            }

                            m.Position = 0;

                            using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                            {
                                result = sr.ReadToEnd();
                            }

                            if ((head.Flag & MessageFlag.IsException) != 0)
                            {
                                string[] strs = Hubble.Framework.Text.Regx.Split(result as string, "innerStackTrace:");

                                result = new InnerServerException(strs[0], strs[1]);
                            }
                        }

                        if (AsyncMessageRecieved != null)
                        {
                            AsyncMessageRecieved(new ASyncPackage(classId, result));
                        }
                    }
                }
                catch (Exception e)
                {
                    lock (this)
                    {
                        Close();
                    }

                    ThreadClosed = true;

                    if (AsyncMessageRecieved != null)
                    {
                        AsyncMessageRecieved(new ASyncPackage(-1, new TcpRemoteCloseException(e.Message)));
                    }
                    return;
                }
            }
        }