Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of <see cref="PipeMessageWriter"/>.
        /// </summary>
        /// <param name="mutexName">The global mutex name.</param>
        /// <param name="messageBuffer">The underlying message buffer implementation.</param>
        public PipeMessageWriter(String mutexName, MessageBuffer messageBuffer)
        {
            Verify.NotWhitespace(mutexName, "mutexName");
            Verify.NotNull(messageBuffer, "messageBuffer");

            this.mutexName = mutexName;
            this.messageBuffer = messageBuffer;
            this.preamble = GetPremable();
        }
Ejemplo n.º 2
0
 public TcpConnection(Socket socket)
 {
     this.Id = Guid.NewGuid();
     this.socket = socket;
     this.buffer = new byte[1];
     var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
     this.connected = true;
     this.Ip = remoteEndPoint.Address;
     this.messageBuffer = new MessageBuffer();
     this.messageBuffer.Message += this.OnMessage;
 }
Ejemplo n.º 3
0
        public PipeMessageWriter(String mutexName, MessageBuffer memoryBuffer)
        {
            Verify.NotWhitespace(mutexName, "mutexName");
            Verify.NotNull(memoryBuffer, "memoryBuffer");

            this.mutexName = mutexName;
            this.memoryBuffer = memoryBuffer;

            using (var process = Process.GetCurrentProcess())
                preamble = BitConverter.GetBytes(process.Id);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of <see cref="OutputDebugStringWriter"/>.
        /// </summary>
        /// <param name="mutexName">The global mutex name.</param>
        /// <param name="messageBuffer">The underlying message buffer implementation.</param>
        public OutputDebugStringWriter(String mutexName, MessageBuffer messageBuffer)
        {
            Verify.NotWhitespace(mutexName, "mutexName");
            Verify.NotNull(messageBuffer, "messageBuffer");

            this.mutexName = mutexName;
            this.messageBuffer = messageBuffer;
            this.buffer = new Byte[OutputDebugString.BufferSize];

            PrepareBufferPreamble();
        }
Ejemplo n.º 5
0
 public Statistics(MessageBuffer buffer,RelaySessionClient client, RelaySessionServer server)
 {
     if (instance != null) throw new Exception("Statistics already exist");
     this.buffer = buffer;
     this.client = client;
     this.server = server;
     cacheSize = new List<long>();
     stateCacheSize = new List<long>();
     channels = new Dictionary<int, int>();
     channelSizes = new Dictionary<int, List<int>>();
     Statistics.instance = this;
 }
        /// <summary>
        /// 接收到应答后处理
        /// </summary>
        /// <param name="reply">WCF应答消息</param>
        /// <param name="correlationState">相关状态</param>
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            //当客户端获取的应答是服务端异常时,尝试反序列化异常并rethrow
            //以免客户端无法解析异常应答而再次引发客户端异常而丢失服务端异常信息
            if (reply.IsFault)
            {
                //创建应答消息副本
                MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
                Message       copy   = buffer.CreateMessage();
                reply = buffer.CreateMessage();

                object    faultDetail = ReadFaultDetail(copy);
                Exception exception   = faultDetail as Exception;
                if (exception != null)
                {
                    throw exception;
                }
            }
        }
        public bool GetMatchingValues(MessageBuffer messageBuffer, ICollection <TFilterData> results)
        {
            if (null == messageBuffer)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
            }
            if (null == results)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
            }

            if (this.CanMatch)
            {
                int count = results.Count;
                this.ProcessMatches(this.iqMatcher.Match(messageBuffer, null), results);
                return(count != results.Count);
            }
            return(false);
        }
        public bool GetMatchingFilters(MessageBuffer messageBuffer, ICollection <MessageFilter> results)
        {
            if (null == messageBuffer)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
            }
            if (null == results)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
            }

            if (this.CanMatch)
            {
                int count = results.Count;
                this.iqMatcher.ReleaseResult(iqMatcher.Match(messageBuffer, results));
                return(count != results.Count);
            }
            return(false);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 发送自己的位置和方向
 /// </summary>
 public void SycMePos()
 {
     for (int i = 0; i < GameManager.instance.ViewManager.MyTeam.Count; i++)
     {
         //Vector3 pos = GameManager.instance.viewMap.CurViewObj.Pos;
         //Vector3 angle = GameManager.instance.viewMap.CurViewObj.EulerAngles;
         //我方每一个对象的位置角度发过去
         Vector3       pos    = GameManager.instance.ViewManager.MyTeam[i].Pos;
         Vector3       angle  = GameManager.instance.ViewManager.MyTeam[i].EulerAngles;
         int           name   = GameManager.instance.ViewManager.MyTeam[i].gameObj.ID;
         MessageBuffer msgBuf = new MessageBuffer();
         msgBuf.WriteInt(cProto.SYNC_POS);
         msgBuf.WriteInt(GameManager.instance.ViewManager.CurViewObj.PlayerID);
         msgBuf.WriteInt(name);
         string cPos = string.Format("{0}#{1}#{2}#{3}#{4}#{5}", pos.x, pos.y, pos.z, angle.x, angle.y, angle.z);
         msgBuf.WriteString(cPos);
         Send(msgBuf);
     }
 }
        public bool GetMatchingFilter(MessageBuffer messageBuffer, out MessageFilter filter)
        {
            if (messageBuffer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
            }

            Message msg = messageBuffer.CreateMessage();

            try
            {
                filter = InnerMatch(msg);
                return(filter != null);
            }
            finally
            {
                msg.Close();
            }
        }
Ejemplo n.º 11
0
        public void ParseMessage(string message)
        {
            MessageType messageType = ClassifyMessage(message);

            if (messageType == MessageType.Spot)
            {
                //If add spot
                //1. Process it.

                //2. Delete any Matching Call and Band
                //3. Add it.
                //Notes: In the case that another contact that shares multipliers is made, you get an Add which is really an update, with the reduced mult status
                //Notes: When you

                Spot s = new Spot(message);

                LogAction("Del/Add", s);
                DeleteSpot(s);
                AddSpot(s);
            }
            else if (messageType == MessageType.SpotDelete || messageType == MessageType.SpotDupe)
            {
                //If delete, or dupe, then parse the Spot delete it.
                Spot s = new Spot(message, true);

                LogAction("Del", s);

                DeleteSpot(s);
            }
            else if (messageType == MessageType.Contact)
            {
                //If Contact, then parse the Contact and delete it.
                Contact c = new Contact(message);

                LogAction("Contact", c);

                DeleteSpot(c);
            }

            MessageBuffer.Add($"{DateTime.Now.ToString("yyyy-dd-mm HH:mm:ss.ffffff")} | {Regex.Replace(message, @"\t|\n|\r", "")}");
            BufferUpdate?.Invoke(this, new SpotAnalysisUpdatedEventArgs());
        }
Ejemplo n.º 12
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                MessageBuffer msgbuf     = reply.CreateBufferedCopy(int.MaxValue);
                Message       tmpMessage = msgbuf.CreateMessage();

                var xdoc = new XDocument();
                using (var wr = xdoc.CreateWriter())
                {
                    tmpMessage.WriteBody(wr);
                }

                var q = from h in xdoc.Root.Elements(NameSpaces.xsoap + "Header")
                        from i in h.Elements(NameSpaces.xsosi + "implicitLoginHeader")
                        from r in i.Elements(NameSpaces.xsosi + "requestIdCardDigestForSigningResponse")
                        select new SosiGWLoginError()
                {
                    DigestValue = r.Element(NameSpaces.xds + "DigestValue").Value,
                    BrowserUrl  = r.Element(NameSpaces.xsosi + "BrowserUrl").Value
                };

                var le     = q.FirstOrDefault();
                var reason = xdoc.Root.Elements(NameSpaces.xsoap + "Body")
                             .Elements(NameSpaces.xsoap + "Fault")
                             .Elements("faultstring")
                             .Select(v => v.Value).FirstOrDefault();
                if (le != null)
                {
                    throw new FaultException <SosiGWLoginError>(le, new FaultReason(reason));
                }

                var dgwsfc = xdoc.Root.Descendants(NameSpaces.xdgws + "FaultCode").FirstOrDefault();
                if (dgwsfc != null)
                {
                    var fs = xdoc.Root.Descendants("faultstring").First();
                    throw new FaultException <XElement>(dgwsfc, new FaultReason(fs.Value), new FaultCode("Server"), null);
                }

                reply = msgbuf.CreateMessage();
            }
        }
Ejemplo n.º 13
0
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var reqxdoc = correlationState as XDocument;

            if (reply.IsFault) //replaces s:Server with Server in faultcode
            {
                MessageBuffer msgbuf = reply.CreateBufferedCopy(int.MaxValue);
                var           r      = msgbuf.CreateMessage();

                var xdoc = new XDocument();
                using (var wr = xdoc.CreateWriter())
                {
                    r.WriteMessage(wr);
                }

                if (xdoc.Descendants("faultstring").First().Value == "requesterror")
                {
                    var fc = xdoc.Descendants(NameSpaces.xdgws + "FaultCode").First();
                    reqxdoc = XDocument.Parse(fc.Value);
                    var xfault = reqxdoc.Root.Element("Fault");
                    xdoc.Descendants("faultstring").First().Value = xfault.Element("reason").Value;
                    fc.Value = xfault.Element("detail").Value;
                }

                xdoc.Descendants("faultcode").First().Value = "Server";
                using (var reader = xdoc.CreateReader())
                {
                    var rmsg = Message.CreateMessage(reader, int.MaxValue, reply.Version).CreateBufferedCopy(int.MaxValue);
                    reply = rmsg.CreateMessage();
                }
            }

            if (reqxdoc != null)
            {
                var msg = reqxdoc.Descendants(NameSpaces.xdgws + "MessageID").First();
                reqxdoc.Descendants(NameSpaces.xdgws + "Linking").First().Add(new XElement(NameSpaces.xdgws + "RequireNonRepudiationReceipt", msg.Value));
                msg.Value = Guid.NewGuid().ToString("D");

                reply.Headers.Add(new DgwsMessageHeader(new DgwsHeader(reqxdoc.Root.Element(NameSpaces.xdgws + "Header"))));
                reqxdoc.Descendants(NameSpaces.xdgws + "FlowStatus").First().Value = "flow_finalized_succesfully";
            }
        }
Ejemplo n.º 14
0
    public void OnMessage(Client c, MessageBuffer msg)
    {
        try
        {
            switch ((Protocol)msg.ReadShort())
            {
            case Protocol.PlayerName:
                map.PlayerJoin(c, msg.ReadString());
                break;
            }

            msg.Reset();
        }
        catch (Exception e)
        {
            Log.Write(ConsoleColor.Yellow, "Packet corrupt!");
            Log.Write(ConsoleColor.Red, e.Message);
            Log.Write(ConsoleColor.DarkRed, e.StackTrace);
        }
    }
Ejemplo n.º 15
0
        //Server Side
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            X509Certificate2 myCert = CryptoHelper.FindCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=klServer");
            var myHash = myCert.GetCertHash();

            var mySignedHash = CryptoHelper.Sign(myHash, myCert);

            var keyChars = new char[mySignedHash.Length];

            for (int i = 0; i < mySignedHash.Length; i++)
            {
                keyChars[i] = (char)mySignedHash[i];
            }

            reply.Headers.Add((new CustomSecurityHeader(new string(keyChars))));

            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);

            reply = buffer.CreateMessage();
        }
        public bool GetMatchingFilter(MessageBuffer messageBuffer, out MessageFilter filter)
        {
            Collection <MessageFilter> filters = new Collection <MessageFilter>();

            this.GetMatchingFilters(messageBuffer, filters);
            if (filters.Count > 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, filters));
            }
            else if (filters.Count == 1)
            {
                filter = filters[0];
                return(true);
            }
            else
            {
                filter = null;
                return(false);
            }
        }
Ejemplo n.º 17
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            MessageBuffer buffer = reply.CreateBufferedCopy(int.MaxValue);
            Message       copy   = buffer.CreateMessage();

            var logger      = Log4NetLogger.Configure();
            var replyString = reply.ToString();

            logger.Information(replyString);
            ReportingService.LogUserActivity(replyString, LogTypes.BankLink);

            var doc = GetDocumentFromMessage(copy);

            if (!VerifySignature(doc))
            {
                throw new SignatureException("Signature is not valid");
            }

            reply = buffer.CreateMessage();
        }
Ejemplo n.º 18
0
        public void TestSimpleMessageBuffer()
        {
            Message m = Message.CreateMessage(MessageVersion.Default,
                                              String.Empty,
                                              new MyBodyWriter());
            MessageBuffer b = m.CreateBufferedCopy(Int32.MaxValue);

            Assert.IsFalse(m.IsEmpty, "#1");
            Assert.AreEqual(0, b.BufferSize, "#2");
            Assert.AreEqual("application/soap+msbin1", b.MessageContentType, "#3");
            // BodyWriter must not be used twice.
            using (XmlWriter w = XmlWriter.Create(TextWriter.Null))
            {
                b.CreateMessage().WriteMessage(w);
            }
            using (XmlWriter w = XmlWriter.Create(TextWriter.Null))
            {
                b.CreateMessage().WriteMessage(w);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns a copy of the message.
        /// </summary>
        /// <returns>the message</returns>
        public Message GetCopy()
        {
            // http://msdn.microsoft.com/en-us/library/ms734675.aspx
            WCFLogger.Write(TraceEventType.Verbose, "InterceptorMessage get copy of message");
            if (this.bufferCopy == null)
            {
                bufferCopy = originalMessage.CreateBufferedCopy(int.MaxValue);
            }

            Message message = bufferCopy.CreateMessage();

            foreach (KeyValuePair <string, object> pair in newProperties)
            {
                string key   = pair.Key;
                object value = pair.Value;
                message.Properties.Add(key, value);
            }

            return(message);
        }
Ejemplo n.º 20
0
    public void OnMessageExternal(IPEndPoint ip, MessageBuffer msg)
    {
        try
        {
            switch ((Protocol)msg.ReadShort())
            {
            case Protocol.RequestInfo:
                trackerHandler.SendInfoTo(ip);
                break;
            }

            msg.Reset();
        }
        catch (Exception e)
        {
            Log.Write(ConsoleColor.Yellow, "Packet corrupt from external!");
            Log.Write(ConsoleColor.Red, e.Message);
            Log.Write(ConsoleColor.DarkRed, e.StackTrace);
        }
    }
Ejemplo n.º 21
0
    public void OnMessage(MessageBuffer msg)
    {
        try
        {
            switch ((Protocol)msg.ReadShort())
            {
            case Protocol.EnterMap:
                LoadMap(msg.ReadByte(), msg.ReadString());
                break;
            }

            msg.Reset();
        }
        catch (Exception e)
        {
            Log.Write(ConsoleColor.Yellow, "Packet corrupt!");
            Log.Write(ConsoleColor.Red, e.Message);
            Log.Write(ConsoleColor.DarkRed, e.StackTrace);
        }
    }
Ejemplo n.º 22
0
    public void SendMemberListToPlayer(params Player[] players)
    {
        foreach (Player p in memberList)
        {
            MessageBuffer msg = new MessageBuffer();

            msg.WriteShort((short)Protocol.PlayerJoinTeam);

            msg.WriteByte(p.id);
            msg.WriteByte(id);

            foreach (Player pp in players)
            {
                if (pp != null)
                {
                    pp.client.Send(msg);
                }
            }
        }
    }
Ejemplo n.º 23
0
    MessageBuffer GetExistanceMessage()
    {
        MessageBuffer msg = new MessageBuffer();

        msg.WriteShort((short)Protocol.MapArgument);
        msg.WriteShort((short)Protocol_SY.TowerExistance);

        msg.WriteByte(id);
        msg.WriteByte(teamID);
        if (point != null)
        {
            msg.WriteByte(point.id);
        }
        else
        {
            msg.WriteVector(position);
        }

        return(msg);
    }
Ejemplo n.º 24
0
            public bool GetMatchingValues(MessageBuffer messageBuffer, ICollection <TFilterData> results)
            {
                if (messageBuffer == null)
                {
                    throw FxTrace.Exception.ArgumentNull("messageBuffer");
                }

                List <MessageFilter> firstPassResults = new List <MessageFilter>();

                if (this.filterTable.GetMatchingFilters(messageBuffer, firstPassResults))
                {
                    IList <StrictAndMessageFilter> matchingFilters = FindMatchingAndFilters(firstPassResults);
                    foreach (StrictAndMessageFilter andFilter in matchingFilters)
                    {
                        results.Add(this.andFilters[andFilter]);
                    }
                    return(matchingFilters.Count > 0);
                }
                return(false);
            }
Ejemplo n.º 25
0
        /// <summary>
        /// Despatches received data from the arg through to terrarias internal buffers
        /// </summary>
        protected virtual void DespatchData(ReceiveArgs args)
        {
            var           id  = this.RemoteClient.Id;
            MessageBuffer obj = NetMessage.buffer[id];

            lock (obj)
            {
                if (!this.RemoteClient.IsActive)
                {
                    this.RemoteClient.IsActive = true;
                    this.RemoteClient.State    = 0;
                }

                Buffer.BlockCopy(args.Buffer, args.Offset, NetMessage.buffer[id].readBuffer, NetMessage.buffer[id].totalData, recvBytes);
                NetMessage.buffer[id].totalData += recvBytes;
                NetMessage.buffer[id].checkBytes = true;

                recvBytes = 0;
            }
        }
Ejemplo n.º 26
0
 public bool GetMatchingFilter(MessageBuffer buffer, out MessageFilter filter)
 {
     filter = null;
     foreach (KeyValuePair <MessageFilter, FilterData> pair in this.filters)
     {
         if (pair.Key.Match(buffer))
         {
             if (filter != null)
             {
                 Collection <MessageFilter> filters = new Collection <MessageFilter> {
                     filter,
                     pair.Key
                 };
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(System.ServiceModel.SR.GetString("FilterMultipleMatches"), null, filters));
             }
             filter = pair.Key;
         }
     }
     return(filter != null);
 }
        public override bool Match(MessageBuffer messageBuffer)
        {
            bool flag;

            if (messageBuffer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
            }
            Message message = messageBuffer.CreateMessage();

            try
            {
                flag = this.Match(message);
            }
            finally
            {
                message.Close();
            }
            return(flag);
        }
Ejemplo n.º 28
0
        static string MessageString(ref Message m)
        {
            MessageBuffer mb = m.CreateBufferedCopy(int.MaxValue);

            m = mb.CreateMessage();
            MemoryStream s  = new MemoryStream();
            XmlWriter    xw = XmlWriter.Create(s);

            m.WriteMessage(xw);
            xw.Flush();
            s.Position = 0;

            var bXml = new byte[s.Length];

            s.Read(bXml, 0, (int)s.Length);

            return(bXml[0] != (byte)'<'
                                ? Encoding.UTF8.GetString(bXml, 3, bXml.Length - 3)
                                : Encoding.UTF8.GetString(bXml, 0, bXml.Length));
        }
Ejemplo n.º 29
0
    private void On_TCP_Message(MessageBuffer msg)
    {
        Debug.Log((ServerToClientID)msg.Id());

        // 请求匹配成功
        if (ServerToClientID.TcpResponseRequestMatch == (ServerToClientID)msg.Id())
        {
            ImageWait.SetActive(true);
        }
        // 取消匹配成功
        else if (ServerToClientID.TcpResponseCancelMatch == (ServerToClientID)msg.Id())
        {
            ImageWait.SetActive(false);
        }
        // 允许进入战场
        else if (ServerToClientID.TcpEnterBattle == (ServerToClientID)msg.Id())
        {
            Debug.Log("进入战场");
        }
    }
Ejemplo n.º 30
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                // Create a copy of the original reply to allow default processing of the message
                MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
                Message       copy   = buffer.CreateMessage();
                reply = buffer.CreateMessage();

                var exception = ReadExceptionFromFaultDetail(copy) as Exception;
                if (exception != null)
                {
                    //if (exception.InnerException != null && exception.InnerException.InnerException != null && exception.InnerException.InnerException.Message != null)
                    //{
                    //    if (exception.InnerException.Message.Equals("A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The wait operation timed out.)") && exception.InnerException.InnerException.Message.Equals("The wait operation timed out"))
                    //        throw exception;
                    //}
                }
            }
        }
Ejemplo n.º 31
0
        internal static T ReadJsonBinary <T>(MessageBuffer messageBuffer, Stream stream, JsonSerializerOptions options)
        {
            if (!messageBuffer.IsBinary)
            {
                throw new InvalidOperationException("Cannot read mixed json-binary data.");
            }
            var buffer     = messageBuffer.RawData.GetBuffer();
            var magic      = BitConverter.ToInt32(buffer, 0);
            var jsonLength = BitConverter.ToInt32(buffer, 4);

            if (magic != 0x58454E4F || jsonLength + 8 > buffer.Length)
            {
                throw new InvalidOperationException("ONEX binary format error.");
            }
            var ret = JsonSerializer.Deserialize <T>(new ReadOnlySpan <byte>(buffer, 8, jsonLength), options);

            messageBuffer.RawData.Position = jsonLength + 8;
            messageBuffer.RawData.CopyTo(stream);
            return(ret);
        }
        public bool GetMatchingValues(MessageBuffer buffer, ICollection <TFilterData> results)
        {
            if (results == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
            }
            int count    = results.Count;
            int priority = -2147483648;

            for (int i = 0; i < this.tables.Count; i++)
            {
                if ((priority > this.tables[i].priority) && (count != results.Count))
                {
                    break;
                }
                priority = this.tables[i].priority;
                this.tables[i].table.GetMatchingValues(buffer, results);
            }
            return(count != results.Count);
        }
Ejemplo n.º 33
0
 private void LoginCon_On_TCP_Message(MessageBuffer msg)
 {
     if (ServerToClientID.TcpResponseRegister == (ServerToClientID)msg.Id())
     {
         TcpResponseRegister _mes = ProtoTransfer.DeserializeProtoBuf3 <TcpResponseRegister>(msg);
         if (_mes.Result)
         {
             Debug.Log("注册成功~~~");
             ClientService.GetSingleton().token = _mes.Token;
             this.gameObject.SetActive(false);
             panel_Login.SetActive(true);
             waitTip.SetActive(false);
         }
         else
         {
             text.text = "注册失败";
             waitTip.SetActive(false);
         }
     }
 }
        // this optimization is only for CorrelationActionMessageFilter and ActionMessageFilter if they override CreateFilterTable to return ActionMessageFilterTable
        internal bool GetMatchingValue(MessageBuffer buffer, Message messageToReadHeaders, out TFilterData data)
        {
            bool dataSet = false;
            int  pri     = int.MinValue;

            data = default(TFilterData);
            for (int i = 0; i < this.tables.Count; ++i)
            {
                // Watch for the end of a bucket
                if (pri > this.tables[i].priority && dataSet)
                {
                    break;
                }
                pri = this.tables[i].priority;

                TFilterData currentData;
                bool        result = false;
                if (messageToReadHeaders != null && this.tables[i].table is ActionMessageFilterTable <TFilterData> )
                {
                    // this is an action message, in this case we can pass in the message itself since the filter will only read from the header
                    result = this.tables[i].table.GetMatchingValue(messageToReadHeaders, out currentData);
                }
                else
                {
                    // this is a custom filter that might read from the message body, pass in the message buffer itself in this case
                    result = this.tables[i].table.GetMatchingValue(buffer, out currentData);
                }
                if (result)
                {
                    if (dataSet)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, null));
                    }

                    data    = currentData;
                    dataSet = true;
                }
            }

            return(dataSet);
        }
Ejemplo n.º 35
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            try
            {
                if (_log.IsDebugEnabled && _IsRawMessageLoggingEnabled)
                {
                    // Log this message.  The thing to be aware of here is that a Message can only be read once.  When I first got this logging working
                    // something else starting throwing an exception that the reply had already been read.  The way to get around this is to first create
                    // a MessageBuffer copy.  Then re-create the reply from the buffer and also create the message to be logged from the buffer.  Here are
                    // some references:
                    // http://msdn.microsoft.com/en-us/library/ms734675.aspx
                    // http://weblogs.asp.net/paolopia/archive/2007/08/23/writing-a-wcf-message-inspector.aspx (though his code ends up logging in the wierd binary format).

                    MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
                    request = buffer.CreateMessage();
                    Message copyToBeLogged = buffer.CreateMessage();

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (
                            XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(memoryStream)
                            )
                        {
                            copyToBeLogged.WriteMessage(xmlDictionaryWriter);
                            xmlDictionaryWriter.Flush();

                            string rawMessage = Encoding.UTF8.GetString(memoryStream.ToArray());

                            _log.Debug("Raw incoming message: " + rawMessage);
                        }
                    }
                }

                return(null);
            }
            catch (Exception exception)
            {
                _log.Error("Error in AfterReceiveRequest.  " + exception.Message, exception);
                throw;
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Begin send the data.
        /// </summary>
        internal void BeginSend(BaseSocketConnection connection, byte[] buffer, bool sentByServer)
        {
            if (Disposed || !connection.Active)
                return;

            byte[] sendBuffer = null;

            try
            {
                if ((connection.Context.EventProcessing == EventProcessing.epUser) && (buffer.Length > Context.MessageBufferSize))
                {
                    throw new MessageLengthException("Message length is greater than Host maximum message length.");
                }

                bool completedAsync = true;
                int bufferSize = 0;

                sendBuffer = BufferUtils.GetPacketBuffer(connection, buffer, ref bufferSize);

                lock (connection.Context.WriteQueue)
                {
                    if (connection.Context.WriteQueueHasItems)
                    {
                        //----- If the connection is sending, enqueue the message!
                        MessageBuffer message = new MessageBuffer(sendBuffer, bufferSize, sentByServer);
                        connection.Context.WriteQueue.Enqueue(message);
                    }
                    else
                    {
                        connection.WriteOV.SetBuffer(sendBuffer, 0, bufferSize);
                        connection.WriteOV.UserToken = new WriteData(connection, sentByServer);

                        //----- If the connection is not sending, send the message!
                        if (connection.Context.Stream != null)
                        {
                            //----- Ssl!
                            connection.Context.Stream.BeginWrite(connection.WriteOV.Buffer, 0, bufferSize, new AsyncCallback(BeginSendCallbackSSL), new WriteData(connection, sentByServer));
                        }
                        else
                        {
                            //----- Socket!
                            completedAsync = connection.Context.SocketHandle.SendAsync(connection.WriteOV);
                        }

                        connection.Context.WriteQueueHasItems = true;
                    }
                }

                sendBuffer = null;

                if (!completedAsync)
                {
                    BeginSendCallbackAsync(this, connection.WriteOV);
                }
            }
            catch (SocketException soex)
            {
                if ((soex.SocketErrorCode == SocketError.ConnectionReset)
                    || (soex.SocketErrorCode == SocketError.ConnectionAborted)
                    || (soex.SocketErrorCode == SocketError.NotConnected)
                    || (soex.SocketErrorCode == SocketError.Shutdown)
                    || (soex.SocketErrorCode == SocketError.Disconnecting))
                {
                    connection.BeginDisconnect();
                }
                else
                {
                    FireOnException(connection, soex);
                }
            }
            catch (Exception ex)
            {
                FireOnException(connection, ex);
            }

            if (sendBuffer != null)
            {
                Context.BufferManager.ReturnBuffer(sendBuffer);
            }
        }
Ejemplo n.º 37
0
        public PipeMessageReader(MessageBuffer memoryBuffer)
        {
            Verify.NotNull(memoryBuffer, "memoryBuffer");

            this.memoryBuffer = memoryBuffer;
        }
Ejemplo n.º 38
0
 public CallbackData(BaseSocketConnection connection, MessageBuffer buffer)
 {
     FConnection = connection;
     FBuffer = buffer;
 }
Ejemplo n.º 39
0
        private ArrayList listthread = new ArrayList(); //记录所有运行的线程

        private void Receive(object param)
        {
            Socket client = param as Socket;
            bool finished = false;
            try
            {
                byte[] btbufundecoded = new byte[0];
                while (!finished)
                {
                    byte[] bufmax = new byte[Config.MAX_LENGTH];
                    int length = client.Receive(bufmax);//接收消息

                    //接收不完整的时候出现问题

                    byte[] btbuf = new byte[length + btbufundecoded.Length];
                    if (btbufundecoded.Length > 0)
                    {
                        Buffer.BlockCopy(btbufundecoded, 0, btbuf, 0, btbufundecoded.Length);//将未完成的字节加入队列的开始
                    }
                    Buffer.BlockCopy(bufmax, 0, btbuf, btbufundecoded.Length, length);//加入接收到的字节
                    MessageBuffer mb = new MessageBuffer(btbuf);
                    if (mb.Completed)
                    {
                        switch (mb.Header)
                        {
                            case MessageType.RequerySolution:
                                {
                                    XmlDocument xmldoc = new XmlDocument();
                                    if (System.IO.File.Exists(Config.SolutionFile))
                                    {
                                        try
                                        {
                                            xmldoc.Load(Config.SolutionFile);
                                        }
                                        catch { }
                                    }
                                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                                    xmldoc.Save(ms);
                                    byte[] xml = ms.ToArray();

                                    MessageBuffer mbsolutionlist = new MessageBuffer(MessageType.SendSolutionList, 0, 0,xml.Length);
                                    mbsolutionlist.SetFileBytes(xml);
                                    client.Send(mbsolutionlist.GetBytes());
                                    finished = true;
                                    break;
                                }

                            case MessageType.RequeryFile:
                                {
                                    UserInfo user = new UserInfo((IPEndPoint)client.RemoteEndPoint);
                                    FileInfoCollection fc = new FileInfoCollection();
                                    fc.Load(mb.GetFileBytes());
                                    user.FilesToDownLoad = Config.LocalFiles.GetDownloadList(fc);
                                    RefreshList(RefreshType.Add, user.ID, user);//增加用户,刷新列表

                                    byte[] xml = user.FilesToDownLoad.SaveToBuffer();
                                    MessageBuffer mbfilelist = new MessageBuffer(MessageType.SendFileList, 0, 0, xml.Length);
                                    mbfilelist.SetFileBytes(xml);
                                    client.Send(mbfilelist.GetBytes());//发送更新列表

                                    user.FilesToDownLoad.Send(client);//发送文件内容
                                    client.Send(MessageBuffer.SendFinished.GetBytes());//发送完毕
                                    break;
                                }
                            case MessageType.RequeryBlock:
                                Config.LocalFiles.Send(client, mb.FileID, mb.FileOffSet, mb.FileLength);//发送文件部分内容
                                break;

                            case MessageType.ReceiveFinished:
                                finished = true;
                                break;
                        }
                    }
                }
            }
            catch (SocketException)//客户端退出或者取消或者超时关闭
            {

            }
            catch//确保服务器稳定
            {
                //记录错误,有心情再做
            }
            finally
            {
                RefreshList(RefreshType.Remove, ((IPEndPoint)client.RemoteEndPoint).ToString().GetHashCode(), null);//移除用户,刷新列表
                client.Close();
            }
        }
 public OutputDebugStringWriter(String mutexName, MessageBuffer messageBuffer)
     : this(mutexName, messageBuffer, new Byte[OutputDebugString.BufferSize])
 {
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates a new instance of <see cref="OutputDebugStringListener"/>.
 /// </summary>
 /// <param name="source">The shared memory source name.</param>
 /// <param name="messageProcessor">The underlying message processor instance.</param>
 /// <param name="messageBuffer">The underlying message buffer instance.</param>
 /// <param name="mutex">The mutex used to indicate a listener is active.</param>
 private OutputDebugStringListener(String source, IProcessMessages messageProcessor, MessageBuffer messageBuffer, Mutex mutex)
     : base(source, messageProcessor, new OutputDebugStringReader(messageBuffer))
 {
     this.mutex = mutex;
     this.messageBuffer = messageBuffer;
 }
        protected void InitializeCryptService(BaseSocketConnection connection)
        { 

          //----- None!
          if (connection.EncryptType == EncryptType.etNone || connection.EncryptType == EncryptType.etBase64)
          {
              FHost.FireOnConnected(connection);
          }

          //----- Symmetric!
          if (connection.EncryptType == EncryptType.etRijndael || connection.EncryptType == EncryptType.etTripleDES)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get RSA provider!
                  RSACryptoServiceProvider serverPublicKey;
                  RSACryptoServiceProvider clientPrivateKey = new RSACryptoServiceProvider();
                  byte[] signMessage;

                  FCryptoService.OnSymmetricAuthenticate(connection, out serverPublicKey, out signMessage);

                  //----- Generates symmetric algoritm!
                  SymmetricAlgorithm sa = CryptUtils.CreateSymmetricAlgoritm(connection.EncryptType);
                  sa.GenerateIV();
                  sa.GenerateKey();

                  //----- Adjust connection cryptors!
                  connection.Encryptor = sa.CreateEncryptor();
                  connection.Decryptor = sa.CreateDecryptor();

                  //----- Create authenticate structure!
                  AuthMessage am = new AuthMessage();
                  am.SessionIV = serverPublicKey.Encrypt(sa.IV, false);
                  am.SessionKey = serverPublicKey.Encrypt(sa.Key, false);
                  am.SourceKey = CryptUtils.EncryptDataForAuthenticate(sa, Encoding.UTF8.GetBytes(clientPrivateKey.ToXmlString(false)), PaddingMode.ISO10126);

                  //----- Sign message with am.SourceKey, am.SessionKey and signMessage!
                  //----- Need to use PaddingMode.PKCS7 in sign!
                  MemoryStream m = new MemoryStream();
                  m.Write(am.SourceKey, 0, am.SourceKey.Length);
                  m.Write(am.SessionKey, 0, am.SessionKey.Length);
                  m.Write(signMessage, 0, signMessage.Length);
                  
                  am.Sign = clientPrivateKey.SignData(CryptUtils.EncryptDataForAuthenticate(sa, m.ToArray(), PaddingMode.PKCS7), new SHA1CryptoServiceProvider());

                  //----- Serialize authentication message!
                  XmlSerializer xml = new XmlSerializer(typeof(AuthMessage));
                  m.SetLength(0);
                  xml.Serialize(m, am);

                  //----- Send structure!
                  MessageBuffer mb = new MessageBuffer(0);
                  mb.PacketBuffer = Encoding.GetEncoding(1252).GetBytes(Convert.ToBase64String(m.ToArray()));
                  connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionSendCallback), new CallbackData(connection, mb));

                  m.Close();
                  am.SessionIV.Initialize();
                  am.SessionKey.Initialize();
                  serverPublicKey.Clear();
                  clientPrivateKey.Clear();

              }
              else
              {

                  //----- Create empty authenticate structure!
                  MessageBuffer mb = new MessageBuffer(8192);

                  //----- Start receive structure!
                  connection.Socket.BeginReceive(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionReceiveCallback), new CallbackData(connection, mb));

              }

          }

          //----- Asymmetric!
          if (connection.EncryptType == EncryptType.etSSL)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get SSL items!
                  X509Certificate2Collection certs = null;
                  string serverName = null;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificateCallback)); 

                  if (certs == null)
                  {
                      ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                  }
                  else
                  {
                      ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));

                  }

              }
              else
              {

                  //----- Get SSL items!
                  X509Certificate2 cert = null;
                  bool clientAuthenticate = false;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket));
                  ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));

              }

          }

        }
Ejemplo n.º 43
0
        /// <summary>
        /// Receive data from connetion.
        /// </summary>
        internal void BeginReceive(BaseSocketConnection connection)
        {

            if (!Disposed)
            {

                try
                {

                    if (connection.Active)
                    {

                        lock (connection.SyncReadCount)
                        {

                            if (connection.ReadCanEnqueue)
                            {

                                if (connection.ReadCount == 0)
                                {

                                    //----- if the connection is not receiving, start the receive!
                                    MessageBuffer readMessage = new MessageBuffer(FSocketBufferSize);

                                    if (connection.Stream != null)
                                    {
                                        //----- Ssl!
                                        connection.Stream.BeginRead(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }
                                    else
                                    {
                                        //----- Socket!
                                        connection.Socket.BeginReceive(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }

                                }

                                //----- Increase the read count!
                                connection.ReadCount++;

                            }

                        }

                    }

                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }

            }

        }
Ejemplo n.º 44
0
 public UdpMessageReader(MessageBuffer messageBuffer)
 {
     this.messageBuffer = messageBuffer;
 }
Ejemplo n.º 45
0
        private void Refresh(IAsyncResult iar)
        {
            try
            {
                client.EndConnect(iar);
            }
            catch (SocketException)
            {
            #region load Server
                IPEndPoint remoteendpoint = (IPEndPoint)iar.AsyncState;
                time.Stop();//停止计时
                try
                {
                    if (LoadServer(remoteendpoint))
                    {
                        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        time.Start();//开始计时
                        client.BeginConnect(remoteendpoint, new AsyncCallback(Refresh), client);
                    }
                    else
                    {
                        SetControlText(labelInfo, labelCanNotConnect.Text);//
                        SetState(State.Idle);
                    }
                    return;
                }
                catch (ObjectDisposedException)
                {
                    SetControlText(labelInfo, labelUpdateCancel.Text);
                    SetState(State.Idle);
                    time.Stop();
                    return;
                }
            #endregion
            }
            catch (ObjectDisposedException)
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
                SetState(State.Idle);
                time.Stop();
                return;
            }

            time.Restart();//开启计时
            try
            {
                client.Send(MessageBuffer.RequerySolution.GetBytes());//发送已经存在文件列表
                byte[] btbufundecoded = new byte[0];//存放上次未处理的娄组

                while (true)
                {
                    byte[] bufmax = new byte[Config.MAX_LENGTH];//存放接收到的数组
                    int length = client.Receive(bufmax);//接收数据
                    time.Restart();//重启计时
                    //重写算法
                    byte[] btbuf = new byte[length + btbufundecoded.Length];//存放接收到及未处理的数组
                    if (btbufundecoded.Length > 0)
                    {
                        Buffer.BlockCopy(btbufundecoded, 0, btbuf, 0, btbufundecoded.Length);//将未完成的字节加入队列的开始
                    }
                    Buffer.BlockCopy(bufmax, 0, btbuf, btbufundecoded.Length, length);//加入接收到的字节

                    btbufundecoded = new byte[0];//清空
                    MessageBuffer mb = new MessageBuffer(btbuf);

                    if (!mb.Completed)//是否完整
                    {
                        btbufundecoded = btbuf;
                    }
                    else
                    {
                        switch (mb.Header)
                        {
                            case MessageType.SendSolutionList:
                                if (mb.FileLength > 0)
                                {
                                    File.WriteAllBytes(Config.SolutionFile, mb.GetFileBytes());
                                    RefreshTreeView();
                                    SetControlText(labelInfo, labelUpdateFinished.Text);
                                    return;
                                }
                                break;
                            default:
                                return;
                                break;
                        }
                    }
                }
            }
            catch (ObjectDisposedException)//按取消连接
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
            }
            catch (Exception e)//有些文件在copy时会有权限问题,还查不出
            {
                SetControlText(labelInfo, e.Message);
            }
            finally
            {
                SetState(State.Idle);
                client.Close();
                time.Stop();
            }
        }
Ejemplo n.º 46
0
        private void Download(IAsyncResult iar)
        {
            try
            {
                client.EndConnect(iar);
            }
            catch (SocketException)
            {
            #region load Server
                IPEndPoint remoteendpoint = (IPEndPoint)iar.AsyncState;
                time.Stop();//停止计时
                try
                {
                    if (LoadServer(remoteendpoint))
                    {
                        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        time.Start();//开始计时
                        client.BeginConnect(remoteendpoint, new AsyncCallback(Download), client);
                    }
                    else
                    {
                        SetControlText(labelInfo, labelCanNotConnect.Text);//
                        SetState(State.Idle);
                    }
                    return;
                }
                catch (ObjectDisposedException)
                {
                    SetControlText(labelInfo, labelUpdateCancel.Text);
                    SetState(State.Idle);
                    time.Stop();
                    return;
                }
                #endregion
            }
            catch (ObjectDisposedException)
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
                SetState(State.Idle);
                time.Stop();
                return;
            }
            time.Stop();//停止计时

            FileInfoCollection fc = new FileInfoCollection();
            if (true)//是否只更新有修改过的文件
            {
                try
                {
                    fc.Load(Config.WorkPath);
                    if (File.Exists("Resume.xml"))                      //存在续传记录
                    {
                        if (MessageBox.Show(this, labelResume.Text, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            XmlDocument xmlresume = new XmlDocument();
                            try
                            {
                                xmlresume.Load("Resume.xml");
                                XmlNode noderesume = xmlresume.SelectSingleNode("Resume/FileResume");
                                int id = Convert.ToInt32(noderesume.Attributes["ID"].Value);
                                DateTime date = Convert.ToDateTime(noderesume.Attributes["Date"].Value);
                                int length = Convert.ToInt32(noderesume.Attributes["Length"].Value);
                                int offset = Convert.ToInt32(noderesume.Attributes["Offset"].Value);
                                fc.SetFiletoResumeInfo(id, date, length, offset);
                            }
                            catch
                            { }
                        }
                        else//清空临时文件夹
                        {
                            Directory.Delete("temp", true);
                            Directory.CreateDirectory("temp");
                        }
                    }
                }
                catch
                {
                    fc.Clear();
                }
                File.Delete("Resume.xml");
            }

            time.Start();//开启计时
            byte[] xml = fc.SaveToBuffer();

            MessageBuffer buf = new MessageBuffer(MessageType.RequeryFile, 0, 0, xml.Length);
            FileStream fs = null;
            buf.SetFileBytes(xml);

            int fileid = 0; //记录当前下载的文件ID
            int fileoffset = 0;//记录当前下载的文件偏移量
            try
            {
                client.Send(buf.GetBytes());//发送已经存在文件列表
                SetControlText(labelInfo, labelDownloadingList.Text);

                int filelength = 0;//记录所有文件的大小
                int filelengthfinished = 0; //记录已经完成的文件的大小

                byte[] btbufundecoded = new byte[0];//存放上次未处理的娄组

                while (true)
                {
                    byte[] bufmax = new byte[Config.MAX_LENGTH];//存放接收到的数组
                    int length = client.Receive(bufmax);//接收数据
                    time.Restart();//重启计时
                    //重写算法
                    byte[] btbuf = new byte[length + btbufundecoded.Length];//存放接收到及未处理的数组
                    if (btbufundecoded.Length > 0)
                    {
                        Buffer.BlockCopy(btbufundecoded, 0, btbuf, 0, btbufundecoded.Length);//将未完成的字节加入队列的开始
                    }
                    Buffer.BlockCopy(bufmax, 0, btbuf, btbufundecoded.Length, length);//加入接收到的字节
                    int bufindex = 0;
                    bool iscompleted = true;
                    while (bufindex < btbuf.Length) //全部处理完也要跳出循环
                    {
                        btbufundecoded = new byte[0];//清空
                        byte[] btmb = new byte[btbuf.Length - bufindex];
                        Buffer.BlockCopy(btbuf, bufindex, btmb, 0, btmb.Length);//将已经处理完的字节移出
                        MessageBuffer mb = new MessageBuffer(btmb);

                        iscompleted = mb.Completed;//判断这个Message是否完整
                        if (!mb.Completed)//是否完整
                        {
                            btbufundecoded = btmb;
                            break;//跳出循环,未处理的在下次接收后一同处理
                        }
                        else
                        {
                            bufindex += mb.FileLength + 13;//修改已经处理的位置
                            switch (mb.Header)
                            {
                                case MessageType.SendFileList:
                                    Config.LocalFiles.Load(mb.GetFileBytes());
                                    filelength = Config.LocalFiles.Length;
                                    break;
                                case MessageType.SendFile:
                                    {
                                        if (fileid != mb.FileID)    //新文件
                                        {
                                            fileid = mb.FileID;
                                            fileoffset = mb.FileOffSet;

                                            if (fs != null)
                                            {
                                                fs.Close();//写回到文件
                                            }
                                            fs = new FileStream(string.Format("temp\\{0}.tmp", fileid), FileMode.OpenOrCreate);
                                            SetControlText(labelInfo, labelDownloading.Text + Config.LocalFiles[fileid].ToString());
                                        }

                                        fs.Position = mb.FileOffSet;
                                        fs.Write(mb.GetFileBytes(), 0, mb.FileLength);//写入到流
                                        fileoffset += mb.FileLength;
                                        filelengthfinished += mb.FileLength;

                                        SetProgressBarValue(progressBarDetail, (int)((double)fileoffset / (double)Config.LocalFiles[fileid].Length * 100));
                                        SetProgressBarValue(progressBarTotal, (int)((double)filelengthfinished / (double)filelength * 100));
                                        //刷新进度条

                                        if (fileoffset == Config.LocalFiles[fileid].Length)//完成这个文件
                                        {
                                            fs.Close();//从流写回到文件
                                            fs = null;
                                            string filename = Config.WorkPath + Config.LocalFiles[fileid].ToString();
                                            if (!Directory.Exists(Path.GetDirectoryName(filename)))//创建目的文件夹
                                            {
                                                Directory.CreateDirectory(Path.GetDirectoryName(filename));
                                            }

                                            if (File.Exists(filename))//如果文件存在则删除
                                            {
                                                File.Delete(filename);
                                            }
                                            File.Move(string.Format("temp\\{0}.tmp", mb.FileID), filename);//移动文件到目的文件夹
                                            File.SetLastWriteTime(filename, Config.LocalFiles[fileid].Date);//设置最后修改时间

                                            Config.LocalFiles.Remove(fileid);
                                        }
                                        break;
                                    }
                                case MessageType.SendFinished:
                                    if (true)
                                    {
                                        client.Send(MessageBuffer.ReceiveFinished.GetBytes());
                                    }
                                    else// 用来申请某个文件中的一部分,可能用不到
                                    {
                                        //MessageBuffer mbreqblock = new MessageBuffer(MessageType.RequeryBlock, "id", "offset", "length");
                                        //client.Send(mbreqblock.GetBytes());
                                    }
                                    if (filelength == 0)
                                    {
                                        SetControlText(labelInfo, labelNoUpdateFound.Text);
                                    }
                                    else
                                    {
                                        SetControlText(labelInfo, labelUpdateFinished.Text);
                                    }
                                    SetProgressBarValue(progressBarDetail, 100);
                                    SetProgressBarValue(progressBarTotal, 100);
                                    client.Shutdown(SocketShutdown.Both);
                                    client.Close(100);
                                    if (true)
                                    {
                                        if (File.Exists(Config.WorkPath + "\\" + Config.PreInstall) && !Config.CheckPreInstall())
                                        {
                                            try
                                            {
                                                System.Diagnostics.Process pro = System.Diagnostics.Process.Start(Config.WorkPath + "\\" + Config.PreInstall);
                                                pro.WaitForInputIdle();
                                            }
                                            catch { }
                                        }
                                        try
                                        {
                                            if (CurrentSolution != null)
                                            {
                                                XmlDocument clientxml = CreateClientXml(CurrentSolution);
                                                clientxml.Save(Config.WorkPath + @"\EEPNetClient.xml");
                                            }
                                        }
                                        catch(Exception e)
                                        {
                                            SetMessageBox(e.Message);
                                        }
                                        try
                                        {
                                            String S = CurrentSolution.Language.ToString() + " " + CurrentSolution.IP +
                                                " " + CurrentSolution.ApPort.ToString();
                                            System.Diagnostics.Process pro
                                                = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Config.WorkPath + "\\" + Config.LaunchPath, S));
                                            pro.WaitForInputIdle();
                                            SetState(State.Idle);
                                            //Application.Exit();
                                        }
                                        catch(Exception e)
                                        {
                                            SetMessageBox(e.Message);
                                        }
                                    }
                                    return;
                            }
                        }
                    }
                }
            }
            catch (Exception e)//有些文件在copy时会有权限问题,还查不出
            {
                if (client.Connected)
                {
                    client.Send(MessageBuffer.ReceiveFinished.GetBytes());
                }
                if (buttonStart.Text == labelStart.Text)
                {
                    SetControlText(labelInfo, labelUpdateCancel.Text);
                    if (fileid != 0 && fileoffset != Config.LocalFiles[fileid].Length)//当前文件未完成
                    {
                        //存入文件
                        XmlDocument xmlresume = new XmlDocument();
                        XmlNode nodedoc = xmlresume.CreateElement("Resume");
                        xmlresume.AppendChild(nodedoc);
                        XmlNode nodefileresume = xmlresume.CreateElement("FileResume");
                        XmlAttribute att = xmlresume.CreateAttribute("ID");
                        att.Value = fileid.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Offset");
                        att.Value = fileoffset.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Date");
                        att.Value = Config.LocalFiles[fileid].Date.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Length");
                        att.Value = Config.LocalFiles[fileid].Length.ToString();
                        nodefileresume.Attributes.Append(att);

                        nodedoc.AppendChild(nodefileresume);
                        xmlresume.Save("Resume.xml");//记录续传文件的信息
                    }
                }
                else
                {
                    SetControlText(labelInfo, string.Empty);
                    SetMessageBox(e.Message);
                }
                SetState(State.Idle);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                //if (!this.Disposing)
                //{
                //    SetState(State.Idle);
                //}
                client.Close();
                time.Stop();
            }
        }
Ejemplo n.º 47
0
        private void ReadBytesFromConnection(CallbackData callbackData, int readBytes)
        {

            BaseSocketConnection connection = callbackData.Connection;
            MessageBuffer readMessage = callbackData.Buffer;

            //----- Has bytes!
            connection.LastAction = DateTime.Now;

            byte[] rawBuffer = null;
            bool socketWasRead = false;
            
            readMessage.PacketOffSet += readBytes;

            switch (connection.DelimiterType)
            {

                case DelimiterType.dtNone:

                    //----- Message with no delimiter!
                    rawBuffer = readMessage.GetRawBuffer(readBytes, 0);

                    break;

                case DelimiterType.dtPacketHeader:

                    //----- Message with packet header!
                    rawBuffer = ReadMessageWithPacketHeader(connection.Delimiter, callbackData, ref socketWasRead);

                    break;

                case DelimiterType.dtMessageTailExcludeOnReceive:
                case DelimiterType.dtMessageTailIncludeOnReceive:


                    //----- Message with tail!
                    rawBuffer = ReadMessageWithMessageTail(connection.Delimiter, callbackData, ref socketWasRead);

                    break;

            }

            if (rawBuffer != null)
            {

                //----- Decrypt!
                //rawBuffer = CryptUtils.DecryptData(connection, rawBuffer, FMessageBufferSize);

                //----- Fire Event!
                FireOnReceived(connection, rawBuffer, true);
                
            }

            readMessage = null;
            callbackData = null;
            
            if(!socketWasRead)
            {

                //----- Check Queue!
                lock (connection.SyncReadCount)
                {

                    connection.ReadCount--;

                    if (connection.ReadCount > 0)
                    {

                        //----- if it need more receiving, start the receive!
                        MessageBuffer continueReadMessage = new MessageBuffer(FSocketBufferSize);

                        //----- if the read queue has items, start to receive!
                        if (connection.Stream != null)
                        {
                            //----- Ssl!
                            connection.Stream.BeginRead(continueReadMessage.PacketBuffer, continueReadMessage.PacketOffSet, continueReadMessage.PacketRemaining, new AsyncCallback(BeginReadCallback), new CallbackData(connection, continueReadMessage));
                        }
                        else
                        {
                            //----- Socket!
                            connection.Socket.BeginReceive(continueReadMessage.PacketBuffer, continueReadMessage.PacketOffSet, continueReadMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginReadCallback), new CallbackData(connection, continueReadMessage));
                        }

                    }

                }

            }

        }
Ejemplo n.º 48
0
        protected void InitializeProxy(BaseSocketConnection connection)
        {

          if (!Disposed)
          {

            try
            {

              if (connection.Active)
              {

                MessageBuffer mb = new MessageBuffer(0);
                mb.PacketBuffer = FProxyInfo.GetProxyRequestData(FRemoteEndPoint);
                connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxySendCallback), new CallbackData(connection, mb));
              }

            }
            catch (Exception ex)
            {
              Host.FireOnException(connection, ex);
            }

          }

        }
Ejemplo n.º 49
0
        private void InitializeProxySendCallback(IAsyncResult ar)
        {

            if (!Disposed)
            {

                BaseSocketConnection connection = null;
                MessageBuffer writeMessage = null;
                CallbackData callbackData = null;

                try
                {

                  callbackData = (CallbackData)ar.AsyncState;
                  connection = callbackData.Connection;
                  writeMessage = callbackData.Buffer;

                  if (connection.Active)
                  {

                    //----- Socket!
                    int writeBytes = connection.Socket.EndSend(ar);

                    if (writeBytes < writeMessage.PacketRemaining)
                    {
                      //----- Continue to send until all bytes are sent!
                      writeMessage.PacketOffSet += writeBytes;
                      connection.Socket.BeginSend(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxySendCallback), callbackData);
                    }
                    else
                    {

                      writeMessage = null;
                      callbackData = null;

                      MessageBuffer readMessage = new MessageBuffer(4096);
                      connection.Socket.BeginReceive(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxyReceiveCallback), new CallbackData(connection, readMessage));

                    }

                  }

                }
                catch (Exception ex)
                {
                  Host.FireOnException(connection, ex);
                }

            }

        }
Ejemplo n.º 50
0
 public void Initialize()
 {
     buffer = new MessageBuffer();
 }
Ejemplo n.º 51
0
 /// <summary>
 /// Creates a new instance of <see cref="PipeMessageListener"/>.
 /// </summary>
 /// <param name="listenerName">The named pipe listener name.</param>
 /// <param name="messageProcessor">The underlying message processor instance.</param>
 /// <param name="messageBuffer">The underlying message buffer instance.</param>
 /// <param name="mutex">The mutex used to indicate a listener is active.</param>
 private PipeMessageListener(String listenerName, IProcessMessages messageProcessor, MessageBuffer messageBuffer, Mutex mutex)
     : base(listenerName, messageProcessor, new PipeMessageReader(messageBuffer))
 {
     this.mutex = mutex;
     this.messageBuffer = messageBuffer;
 }