void OnAccept(IAsyncResult ar)
        {
            try
            {
                if (shuttingDown)
                    return;

                Socket serverSocket = (Socket)ar.AsyncState;
                Socket clientSocket = serverSocket.EndAccept(ar);

                // Get ready for next incoming connection.
                serverSocket.BeginAccept(OnAccept, serverSocket);

                if (!clientSocket.Connected)
                    return;

                var sc = new SocketConnection(clientSocket);

                lock (synclock)
                    connections.Add(sc);

                try
                {
                    sc.Socket.BeginReceive(sc.SocketBuffer, 0, sc.BufferSize, SocketFlags.None, OnReceive, sc);
                }
                catch (Exception ex)
                {
                    Logger.Error("An error has occured while trying to receive data from the client. Exception = {0}", LogSource.AppServer, ex);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("An error has occured while trying to accept a new connection from the client. Exception = {0}", LogSource.AppServer, ex);
            }
        }
        void CloseConnection(SocketConnection sc)
        {
            lock (synclock)
                connections.Remove(sc);

            sc.Close();
        }
 internal SocketActor(SocketConnection connection)
     : base(connection)
 {
     _connection = connection;
 }
示例#4
0
 /// <inheritdoc />
 protected override Task <bool> Unsubscribe(SocketConnection connection, SocketSubscription s)
 {
     return(Task.FromResult(true));
 }
示例#5
0
 /// <inheritdoc />
 protected override bool HandleSubscriptionResponse(SocketConnection s, SocketSubscription subscription, object request, JToken message, out CallResult <object>?callResult)
 {
     throw new NotImplementedException();
 }
示例#6
0
    static async Task Main()
    {
        try
        {
            // need to put these somewhere that isn't the repo; maybe a json file that
            // is in the .gitignore?
            const int RedisPort = 6379;
            string    host      = "localhost";
            string    password  = null; // <=== azure auth key

            await Console.Out.WriteLineAsync($"resolving ip of '{host}'...");

            var ip = (await Dns.GetHostAddressesAsync(host)).First();



            await Console.Out.WriteLineAsync($"connecting to '{ip}:{RedisPort}'...");

            using (var connection = await SocketConnection.ConnectAsync(new IPEndPoint(ip, RedisPort)))
            {
                if (password != null)
                {
                    await WriteSimpleMessage(connection.Output, $"AUTH \"{password}\"");

                    // a "success" for this would be a response that says "+OK"
                }

                await WriteSimpleMessage(connection.Output, "ECHO \"noisy in here\"");

                // note that because of RESP, this actually gives 2 replies; don't worry about it :)

                await WriteSimpleMessage(connection.Output, "PING");


                var input = connection.Input;
                while (true)
                {
                    await Console.Out.WriteLineAsync($"awaiting response...");

                    var result = await input.ReadAsync();

                    await Console.Out.WriteLineAsync($"checking response...");

                    var buffer = result.Buffer;

                    if (buffer.IsEmpty && result.IsCompleted)
                    {
                        await Console.Out.WriteLineAsync($"done");

                        break;
                    }

                    if (!buffer.TrySliceTo((byte)'\r', (byte)'\n', out var slice, out var cursor))
                    {
                        await Console.Out.WriteLineAsync($"incomplete");

                        input.Advance(buffer.Start, buffer.End);
                        continue;
                    }
                    var reply = slice.GetAsciiString();
                    await Console.Out.WriteLineAsync($"<< received: '{reply}'");

                    if (string.Equals(reply, "+PONG", StringComparison.OrdinalIgnoreCase))
                    {
                        await WriteSimpleMessage(connection.Output, "QUIT");

                        connection.Output.Complete();
                    }

                    // input.Advance(cursor); // feels like this should work, but it doesn't
                    var incTerminator = buffer.Slice(0, slice.Length + 2);
                    input.Advance(incTerminator.End, incTerminator.End);
                }
            }
        }
        catch (Exception ex)
        {
            await Console.Error.WriteLineAsync(ex.Message);
        }
    }
示例#7
0
        private IConnection CreateConnection(Socket clientSocket)
        {
            var socketConnection = SocketConnection.Create(clientSocket);

            return(new Connection(socketConnection, this.decryptorCreator(socketConnection.Input), this.encryptorCreator(socketConnection.Output)));
        }
示例#8
0
 protected override bool HandleQueryResponse <T>(SocketConnection s, object request, JToken data, out CallResult <T> callResult)
 {
     return(this.BtcTurkHandleQueryResponse <T>(s, request, data, out callResult));
 }
 public static async Task <SimplPipelineClient> ConnectAsync(EndPoint endpoint)
 => new SimplPipelineClient(await SocketConnection.ConnectAsync(endpoint));
示例#10
0
 public static Connection GetAscensionConnection(this SocketConnection self)
 {
     return((Connection)self.UserToken);
 }
示例#11
0
 internal void method_8(uint uint_0, ref SocketConnection Message1_0)
 {
     this.Clients[(int)((uint)((UIntPtr)uint_0))] = new GameClient(uint_0, ref Message1_0);
     this.Clients[(int)((uint)((UIntPtr)uint_0))].GetSocketConnection();
 }
示例#12
0
文件: Look.cs 项目: xuesong/ModernMUD
        /// <summary>
        /// Show a character to another character.
        /// </summary>
        /// <param name="victim"></param>
        /// <param name="ch"></param>
        public static void ShowCharacterToCharacterFull(CharData victim, CharData ch)
        {
            Object obj;
            string text = String.Empty;
            int    percent;

            if (CharData.CanSee(victim, ch))
            {
                SocketConnection.Act("$n&n looks at you.", ch, null, victim, SocketConnection.MessageTarget.victim);
                if (victim != ch)
                {
                    SocketConnection.Act("$n&n looks at $N&n.", ch, null, victim, SocketConnection.MessageTarget.everyone_but_victim);
                }
                else
                {
                    SocketConnection.Act("$n&n looks at $mself.", ch, null, victim, SocketConnection.MessageTarget.everyone_but_victim);
                }
            }

            if (victim.Riding != null)
            {
                text += String.Format("&nMounted on {0}, ", victim.Riding.ShowNameTo(ch, false));
            }
            else if (victim.Rider != null)
            {
                text += String.Format("&nRidden by {0}, ", victim.Rider.ShowNameTo(ch, false));
            }

            if (!victim.IsNPC() && victim.IsGuild())
            {
                text += String.Format("&n{0} of {1}.\r\n", ((PC)victim).GuildRank.ToString().ToUpper(),
                                      ((PC)victim).GuildMembership.Name);
            }

            SocketConnection.Act(text, ch, null, victim, SocketConnection.MessageTarget.character);

            if (!String.IsNullOrEmpty(victim.Description))
            {
                ch.SendText(victim.Description);
            }
            else
            {
                SocketConnection.Act("&nYou see nothing special about $M.", ch, null, victim, SocketConnection.MessageTarget.character);
            }

            if (victim.GetMaxHit() > 0)
            {
                percent = (100 * victim.Hitpoints) / victim.GetMaxHit();
            }
            else
            {
                percent = -1;
            }

            text = victim.ShowNameTo(ch, true);

            if (percent >= 100)
            {
                text += " &nis in perfect &n&+ghealth&n.  ";
            }
            else if (percent >= 90)
            {
                text += " &nis slightly &n&+yscratched&n.  ";
            }
            else if (percent >= 80)
            {
                text += " &nhas a &+yfew bruises&n.  ";
            }
            else if (percent >= 70)
            {
                text += " &nhas &+Ysome cuts&n.  ";
            }
            else if (percent >= 60)
            {
                text += " &nhas &+Mseveral wounds&n.  ";
            }
            else if (percent >= 50)
            {
                text += " &nhas &+mmany nasty wounds&n.  ";
            }
            else if (percent >= 40)
            {
                text += " &nis &+Rbleeding freely&n.  ";
            }
            else if (percent >= 30)
            {
                text += " &nis &+Rcovered in blood&n.  ";
            }
            else if (percent >= 20)
            {
                text += " &nis &+rleaking guts&n.  ";
            }
            else if (percent >= 10)
            {
                text += " &nis &+ralmost dead&n.  ";
            }
            else
            {
                text += " &nis &+rDYING&n.  ";
            }

            ch.SendText(text);

            // Show size on look at someone.
            text = MUDString.CapitalizeANSIString(String.Format("{0}&n is a {1} of {2} size.\r\n", victim.GetSexPronoun(),
                                                                Race.RaceList[victim.GetRace()].ColorName, Race.SizeString(victim.CurrentSize)));
            ch.SendText(text);

            ShowAffectLines(ch, victim);

            bool found = false;

            foreach (ObjTemplate.WearLocation location in ObjTemplate.TopDownEquipment)
            {
                obj = Object.GetEquipmentOnCharacter(victim, location);
                if (obj && CharData.CanSeeObj(ch, obj))
                {
                    if (!found)
                    {
                        ch.SendText("\r\n");
                        SocketConnection.Act("&n$E is using:", ch, null, victim, SocketConnection.MessageTarget.character);
                        found = true;
                    }
                    if (obj.ItemType == ObjTemplate.ObjectType.weapon &&
                        (location == ObjTemplate.WearLocation.hand_one ||
                         location == ObjTemplate.WearLocation.hand_three ||
                         location == ObjTemplate.WearLocation.hand_four ||
                         location == ObjTemplate.WearLocation.hand_two) &&
                        obj.HasWearFlag(ObjTemplate.WEARABLE_WIELD))
                    {
                        if (obj.HasFlag(ObjTemplate.ITEM_TWOHANDED) &&
                            !ch.HasInnate(Race.RACE_EXTRA_STRONG_WIELD))
                        {
                            ch.SendText("&+y(wielding twohanded)  &n");
                        }
                        else
                        {
                            ch.SendText("&+y(wielding)            &n");
                        }
                    }
                    else
                    {
                        if (obj.ItemType == ObjTemplate.ObjectType.shield &&
                            (location == ObjTemplate.WearLocation.hand_one ||
                             location == ObjTemplate.WearLocation.hand_three ||
                             location == ObjTemplate.WearLocation.hand_four ||
                             location == ObjTemplate.WearLocation.hand_two) &&
                            obj.HasWearFlag(ObjTemplate.WEARABLE_SHIELD))
                        {
                            ch.SendText("&+y(worn as shield)      &n");
                        }
                        else
                        {
                            ch.SendText(StringConversion.EquipmentLocationDisplay[(int)location]);
                        }
                    }
                    ch.SendText(FormatObjectToCharacter(obj, ch, true));
                    ch.SendText("\r\n");
                }
            }

            // Keep in mind that players can spam looking at someone in order
            // to increase their skill in peek - this will need to be fixed.
            if ((victim != ch && !ch.IsNPC() &&
                 ((((PC)ch).SkillAptitude.ContainsKey("peek") && MUDMath.NumberPercent() < ((PC)ch).SkillAptitude["peek"]) ||
                  ch.Level >= Limits.LEVEL_AVATAR)) || ch.Riding == victim || ch.Rider == victim)
            {
                ch.SendText("\r\n&nYou peek at the inventory:\r\n");
                ch.PracticeSkill("peek");
                ShowListToCharacter(victim.Carrying, ch, true, true);
            }

            return;
        }
示例#13
0
文件: Look.cs 项目: xuesong/ModernMUD
 /// <summary>
 /// Shows what a player or mob is affected by.
 /// </summary>
 /// <param name="ch"></param>
 /// <param name="target"></param>
 public static void ShowAffectLines(CharData ch, CharData target)
 {
     if (target.IsAffected(Affect.AFFECT_BREATHE_UNDERWATER))
     {
         SocketConnection.Act("&+c$E has little gills in $s neck.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_SOULSHIELD))
     {
         if (target.Alignment > 0)
         {
             SocketConnection.Act("&+W$E is surrounded by a holy aura.&n", ch, null, target, SocketConnection.MessageTarget.character);
         }
         else
         {
             SocketConnection.Act("&+r$E is surrounded by an unholy aura.&n", ch, null, target, SocketConnection.MessageTarget.character);
         }
     }
     if (target.IsAffected(Affect.AFFECT_SANCTUARY))
     {
         SocketConnection.Act("&+W$E&+W is surrounded by an white aura.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_STONESKIN))
     {
         SocketConnection.Act("&+L$S skin appears to be made from stone.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_BARKSKIN))
     {
         SocketConnection.Act("&+y$S skin resembles the bark of a tree.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_MAJOR_GLOBE) ||
         target.IsAffected(Affect.AFFECT_MINOR_GLOBE))
     {
         SocketConnection.Act("&+R$E is surrounded by a shimmering globe.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_GREATER_SPIRIT_WARD))
     {
         SocketConnection.Act("&+W$E is surrounded by a diffuse globe of light!&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_COLDSHIELD))
     {
         SocketConnection.Act("&+B$E is surrounded by a killing frost!&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsAffected(Affect.AFFECT_FIRESHIELD))
     {
         SocketConnection.Act("&+r$E is surrounded by a flaming shield.&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
     if (target.IsClass(CharClass.Names.monk) || target.IsClass(CharClass.Names.mystic))
     {
         string stance = null;
         if (ch.IsImmortal() ||
             ch.IsClass(CharClass.Names.monk) || ch.IsClass(CharClass.Names.mystic))
         {
             if (!target.IsNPC())
             {
                 stance = ((PC)target).Stance;
             }
             string text;
             if (!String.IsNullOrEmpty(stance))
             {
                 text = String.Format("&+y$E has assumed the {0} stance.&n", Database.MonkSkillList[stance].Name);
             }
             else
             {
                 text = String.Format("&+y$E stands at ease.&n");
             }
             SocketConnection.Act(text, ch, null, target, SocketConnection.MessageTarget.character);
         }
     }
     if (target.IsAffected(Affect.AFFECT_BOUND))
     {
         SocketConnection.Act("&+y$E is bound and cannot move!&n", ch, null, target, SocketConnection.MessageTarget.character);
     }
 }
示例#14
0
        /// <summary>
        /// Generic spell processing function.  Handles basic spells based on values set in the spell file.
        /// </summary>
        /// <param name="ch"></param>
        /// <param name="level"></param>
        /// <param name="target"></param>
        public void GenericSpellFunction(CharData ch, int level, Target target)
        {
            switch (ValidTargets)
            {
            case TargetType.singleCharacterOffensive:
            {
                CharData opponent = (CharData)target;

                if (level > LevelCap)
                {
                    level = LevelCap;
                }

                int damage = MUDMath.Dice(level, DamageDicePerLevel) + BaseDamage;

                bool saved   = Magic.SpellSavingThrow(level, opponent, DamageInflicted);
                bool affects = true;

                if (saved)
                {
                    switch (SavingThrowEffect)
                    {
                    case SavingThrowResult.negates:
                        damage  = 0;
                        affects = false;
                        ch.SendText("Nothing happens.\r\n");
                        return;

                    case SavingThrowResult.halfDamage:
                        damage /= 2;
                        affects = true;
                        break;

                    case SavingThrowResult.halfDamageNoAffects:
                        damage /= 2;
                        affects = true;
                        break;

                    case SavingThrowResult.fullDamageNoAffects:
                        affects = false;
                        break;

                    case SavingThrowResult.none:
                        affects = true;
                        break;
                    }
                }

                if (damage > 0)
                {
                    Combat.InflictSpellDamage(ch, opponent, damage, this, DamageInflicted);
                }

                if (affects)
                {
                    // Apply "negates" to character.
                    for (int n = 0; n < Negates.Length; n++)
                    {
                        opponent.RemoveAffect(new Bitvector(n, Negates[n]));
                    }
                    Affect af = new Affect();
                    af.Level      = ch.Level;
                    af.BitVectors = Provides;
                    af.Value      = Name;
                    af.Type       = Affect.AffectType.spell;
                    for (int p = 0; p < Provides.Length; p++)
                    {
                        if (Provides[p] != 0)
                        {
                            if (!ch.IsAffected(new Bitvector(p, Provides[p])))
                            {
                                opponent.AddAffect(af);
                                if (!String.IsNullOrEmpty(MessageCompleted))
                                {
                                    SocketConnection.Act(MessageCompleted, ch, null, null, SocketConnection.MessageTarget.character);
                                }
                                else
                                {
                                    ch.SendText("Ok.\r\n");
                                }
                                if (!String.IsNullOrEmpty(MessageCompletedToTarget))
                                {
                                    SocketConnection.Act(MessageCompletedToTarget, ch, opponent, null, SocketConnection.MessageTarget.victim);
                                }
                                if (!String.IsNullOrEmpty(MessageCompletedToRoom))
                                {
                                    SocketConnection.Act(this.MessageCompletedToRoom, ch, opponent, null, SocketConnection.MessageTarget.room);
                                }
                            }
                            else
                            {
                                switch (StackingType)
                                {
                                case StackType.addDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell addDuration stacking types are not yet supported.");

                                case StackType.addModifier:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell addModifier stacking types are not yet supported.");

                                case StackType.addModifierAddDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell addModifierAddDuration stacking types are not yet supported.");

                                case StackType.addModifierMaxDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell addModifierMaxDuration stacking types are not yet supported.");

                                case StackType.alwaysReplace:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell alwaysReplace stacking types are not yet supported.");

                                case StackType.noRefresh:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    break;

                                case StackType.replaceDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell replaceDuration stacking types are not yet supported.");

                                case StackType.takeMaxDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell takeMaxDuration stacking types are not yet supported.");

                                case StackType.takeMaxModifier:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell takeMaxModifier stacking types are not yet supported.");

                                case StackType.takeMaxModifierAndDuration:
                                    ch.SendText("Your spell has no effect.\r\n");
                                    throw new NotSupportedException("Spell takeMaxModifierAndDuration stacking types are not yet supported.");
                                }
                            }
                        }
                    }
                }

                return;
            }

            case TargetType.singleCharacterDefensive:
            case TargetType.self:
            {
                CharData victim;
                if (ValidTargets == TargetType.self)
                {
                    victim = ch;
                }
                else
                {
                    victim = (CharData)target;
                    if (victim == null)
                    {
                        victim = ch;
                    }
                }

                for (int n = 0; n < Negates.Length; n++)
                {
                    victim.RemoveAffect(new Bitvector(n, Negates[n]));
                }

                Affect af = new Affect();
                af.Level      = ch.Level;
                af.BitVectors = Provides;
                af.Value      = Name;
                af.Type       = Affect.AffectType.spell;
                switch (this.Duration)
                {
                case SpellDurationType.oneHourPerlevel:
                    af.Duration = level;
                    break;

                case SpellDurationType.quarterHourPerLevel:
                    af.Duration = level / 4;
                    break;

                case SpellDurationType.halfHourPerLevel:
                    af.Duration = level / 2;
                    break;

                case SpellDurationType.oneDay:
                    af.Duration = 24;
                    break;

                case SpellDurationType.threeHoursPerLevel:
                    af.Duration = level * 3;
                    break;

                case SpellDurationType.twoHoursPerLevel:
                    af.Duration = level * 2;
                    break;

                case SpellDurationType.fourHoursPerLevel:
                    af.Duration = level * 4;
                    break;

                case SpellDurationType.oneHour:
                    af.Duration = 1;
                    break;

                case SpellDurationType.permanent:
                    af.Duration = -1;
                    break;

                case SpellDurationType.sixHours:
                    af.Duration = 6;
                    break;

                case SpellDurationType.threeHours:
                    af.Duration = 3;
                    break;

                case SpellDurationType.twoHours:
                    af.Duration = 2;
                    break;

                default:
                    throw new NotSupportedException("Spells with duration type " + Duration + " are not implemented yet.");
                }
                foreach (AffectApplyType apply in Modifies)
                {
                    af.AddModifier(apply.Location, apply.Amount);
                }

                for (int p = 0; p < Provides.Length; p++)
                {
                    if (Provides[p] != 0)
                    {
                        if (!ch.IsAffected(new Bitvector(p, Provides[p])))
                        {
                            victim.AddAffect(af);
                            if (!String.IsNullOrEmpty(MessageCompleted))
                            {
                                SocketConnection.Act(MessageCompleted, ch, null, null, SocketConnection.MessageTarget.character);
                            }
                            else
                            {
                                ch.SendText("Ok.\r\n");
                            }
                            if (!String.IsNullOrEmpty(MessageCompletedToTarget))
                            {
                                SocketConnection.Act(MessageCompletedToTarget, ch, victim, null, SocketConnection.MessageTarget.victim);
                            }
                            if (!String.IsNullOrEmpty(MessageCompletedToRoom))
                            {
                                SocketConnection.Act(MessageCompletedToRoom, ch, victim, null, SocketConnection.MessageTarget.room);
                            }
                        }
                        else
                        {
                            switch (StackingType)
                            {
                            case StackType.addDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell addDuration stacking types are not yet supported.");

                            case StackType.addModifier:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell addModifier stacking types are not yet supported.");

                            case StackType.addModifierAddDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell addModifierAddDuration stacking types are not yet supported.");

                            case StackType.addModifierMaxDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell addModifierMaxDuration stacking types are not yet supported.");

                            case StackType.alwaysReplace:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell alwaysReplace stacking types are not yet supported.");

                            case StackType.noRefresh:
                                ch.SendText("Your spell has no effect.\r\n");
                                break;

                            case StackType.replaceDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell replaceDuration stacking types are not yet supported.");

                            case StackType.takeMaxDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell takeMaxDuration stacking types are not yet supported.");

                            case StackType.takeMaxModifier:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell takeMaxModifier stacking types are not yet supported.");

                            case StackType.takeMaxModifierAndDuration:
                                ch.SendText("Your spell has no effect.\r\n");
                                throw new NotSupportedException("Spell takeMaxModifierAndDuration stacking types are not yet supported.");
                            }
                        }
                    }
                }
            }
            break;

            case TargetType.multipleCharacterOffensive:
            {
            }
            break;

            case TargetType.objectCorpse:
            {
            }
            break;

            case TargetType.objectInInventory:
            {
            }
            break;

            case TargetType.objectInRoom:
            {
            }
            break;

            case TargetType.objectOrCharacter:
            {
            }
            break;

            case TargetType.ritual:
            {
            }
            break;

            case TargetType.singleCharacterRanged:
            {
                CharData opponent = (CharData)target;

                if (level > LevelCap)
                {
                    level = LevelCap;
                }

                int damage = MUDMath.Dice(level, DamageDicePerLevel) + BaseDamage;

                bool saved   = Magic.SpellSavingThrow(level, opponent, DamageInflicted);
                bool affects = true;

                if (saved)
                {
                    switch (SavingThrowEffect)
                    {
                    case SavingThrowResult.negates:
                        damage  = 0;
                        affects = false;
                        break;

                    case SavingThrowResult.halfDamage:
                        damage /= 2;
                        affects = true;
                        break;

                    case SavingThrowResult.halfDamageNoAffects:
                        damage /= 2;
                        affects = false;
                        break;

                    case SavingThrowResult.fullDamageNoAffects:
                        affects = false;
                        break;

                    case SavingThrowResult.none:
                        affects = true;
                        break;
                    }
                }

                if (damage > 0)
                {
                    Combat.InflictSpellDamage(ch, opponent, damage, this, DamageInflicted);
                }

                if (affects)
                {
                    // TODO: Apply "provides" to character.
                    // TODO: Apply "negates" to character.
                }

                return;
            }

            case TargetType.singleCharacterWorld:
            {
            }
            break;

            case TargetType.trap:
            {
            }
            break;

            case TargetType.none:
            {
                Log.Error("Magic spell '" + Name + "' is flagged as TargetType.none.  This should never happen.  Fix it.");
            }
            break;
            }
        }
示例#15
0
        /// <summary>
        /// Creating a portal.
        /// </summary>
        /// <param name="ch"></param>
        /// <param name="spell"></param>
        /// <param name="level"></param>
        /// <param name="target"></param>
        /// <param name="indexNumber"></param>
        public static void MakePortal(CharData ch, Spell spell, int level, Target target, int indexNumber)
        {
            Room     location;
            CharData victim   = (CharData)target;
            Room     original = ch.InRoom;

            if (ch.IsNPC())
            {
                return;
            }
            if (!victim)
            {
                ch.SendText("Who exactly is your target?\r\n");
                return;
            }
            if (victim.IsNPC() && !ch.IsImmortal())
            {
                return;
            }

            if (!Magic.HasSpellConsent(ch, victim))
            {
                return;
            }

            if (victim == ch || ch.InRoom == victim.InRoom)
            {
                ch.SendText("Seems like a waste of time.\r\n");
                return;
            }

            if (!(location = victim.InRoom) ||
                victim.InRoom.HasFlag(RoomTemplate.ROOM_SAFE) ||
                victim.InRoom.HasFlag(RoomTemplate.ROOM_PRIVATE) ||
                victim.InRoom.HasFlag(RoomTemplate.ROOM_SOLITARY))
            {
                ch.SendText("You can't seem to get a fix their location.\r\n");
                return;
            }
            if (!victim.IsNPC() && (ch.IsRacewar(victim)) && !ch.IsImmortal())
            {
                ch.SendText("Don't you wish it was that easy!\r\n");
                return;
            }

            Object portal = Database.CreateObject(Database.GetObjTemplate(indexNumber), 0);

            if (victim.InRoom.HasFlag(RoomTemplate.ROOM_NO_GATE) ||
                ch.InRoom.HasFlag(RoomTemplate.ROOM_NO_GATE))
            {
                SocketConnection.Act("$p opens for a brief instant and then collapses.&n", ch, portal, null, SocketConnection.MessageTarget.character);
                SocketConnection.Act("$p opens for a brief instant and then collapses.&n", ch, portal, null, SocketConnection.MessageTarget.room);
                SocketConnection.Act("$p opens for a brief instant and then collapses.&n", victim, portal, null, SocketConnection.MessageTarget.character);
                SocketConnection.Act("$p opens for a brief instant and then collapses.&n", victim, portal, null, SocketConnection.MessageTarget.room);
                portal.RemoveFromWorld();
                return;
            }

            portal.Timer     = level / 15;
            portal.Values[2] = level / 7;
            portal.Values[0] = location.IndexNumber;

            portal.AddToRoom(original);

            portal           = Database.CreateObject(Database.GetObjTemplate(indexNumber), 0);
            portal.Timer     = level / 15;
            portal.Values[2] = level / 7;
            portal.Values[0] = original.IndexNumber;

            portal.AddToRoom(location);

            switch (indexNumber)
            {
            case StaticObjects.OBJECT_NUMBER_PORTAL:
                SocketConnection.Act("$p&+Y rises up from the ground.&n", ch, portal, null, SocketConnection.MessageTarget.room);
                SocketConnection.Act("$p&+Y rises up before you.&n", ch, portal, null, SocketConnection.MessageTarget.character);

                if (location.People.Count > 0)
                {
                    SocketConnection.Act("$p&+Y rises up from the ground.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.room);
                    SocketConnection.Act("$p&+Y rises up from the ground.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.character);
                }
                break;

            case StaticObjects.OBJECT_NUMBER_MOONWELL:
                SocketConnection.Act("&+WSilver mists swirl and form into a $p.&n", ch, portal, null, SocketConnection.MessageTarget.room);
                SocketConnection.Act("&+WSilver mists swirl and form into a $p.&n", ch, portal, null, SocketConnection.MessageTarget.character);

                if (location.People.Count > 0)
                {
                    SocketConnection.Act("&+WSilver mists swirl and form into a $p.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.room);
                    SocketConnection.Act("&+WSilver mists swirl and form into a $p.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.character);
                }
                break;

            case StaticObjects.OBJECT_NUMBER_WORMHOLE:
                SocketConnection.Act("$p&+L appears from a warping of space and time.&n", ch, portal, null, SocketConnection.MessageTarget.room);
                SocketConnection.Act("$p&+L appears from a warping of space and time.&n", ch, portal, null, SocketConnection.MessageTarget.character);

                if (location.People.Count > 0)
                {
                    SocketConnection.Act("$p&+L appears from a warping of space and time.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.room);
                    SocketConnection.Act("$p&+L appears from a warping of space and time.&n", location.People[0], portal, null,
                                         SocketConnection.MessageTarget.character);
                }
                break;
            }

            ch.WaitState(8);

            return;
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach (KeyValuePair<int, Connection> p in mConnections)
                {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.handle, handle);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.opType, connOp);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maConnect(" + url + ")\n");
                if (url.StartsWith("btspp"))
                    return MoSync.Constants.CONNERR_UNAVAILABLE;
                Uri uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return MoSync.Constants.CONNERR_GENERIC;
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                if (_conn == MoSync.Constants.HANDLE_LOCAL) // unavailable
                    return -1;
                Connection c = mConnections[_conn];
                return c.getAddr(core.GetDataMemory(), _addr);
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                    CommDelegate cd)
            {
                Connection c = mConnections[_conn];
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream s = (Stream)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                MemoryStream mem = null;
                if (s.GetType() == typeof(MemoryStream))
                {
                    mem = (MemoryStream)s;
                }
                else
                {
                    MoSync.Util.CriticalError("Only binaries (non-ubins) are allowed for maConn(Read/Write)(To/From)Data");
                }

                cd(c, mem.GetBuffer(),
                        delegate(int handle, int connOp, int result)
                        {
                            runtime.SetResourceRaw(_data, res);
                            mResultHandler(handle, connOp, result);
                        });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                        delegate(Connection c, byte[] buf, ResultHandler rh)
                        {
                            c.recv(buf, _offset, _size, rh);
                        });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                        delegate(Connection c, byte[] buf, ResultHandler rh)
                        {
                            c.write(buf, _offset, _size, rh);
                        });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maHttpCreate(" + url + ")\n");
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                if (value.Length > 0)
                    c.setRequestHeader(key, value);
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
示例#17
0
        /// <summary>
        /// Summoning an elemental.
        /// </summary>
        /// <param name="ch"></param>
        /// <param name="spell"></param>
        /// <param name="level"></param>
        /// <param name="indexNumber"></param>
        public static void SummonElem(CharData ch, Spell spell, int level, int indexNumber)
        {
            int numpets = 0;

            foreach (CharData petChar in Database.CharList)
            {
                if (petChar != ch && petChar.Master == ch &&
                    petChar.IsNPC() && petChar.HasActionBit(MobTemplate.ACT_PET))
                {
                    numpets++;
                }
            }

            //just a WAG as far as number...check for some consistency with necro
            int maxpets = ch.Level / 20 + ch.GetCurrCha() / 35;

            if (ch.Level >= Limits.LEVEL_AVATAR)
            {
                string text = String.Format("You can summon at most {0} pets.\r\n", maxpets);
                ch.SendText(text);
            }
            if (numpets >= maxpets)
            {
                ch.SendText("You cannot handle any more pets!\r\n");
                return;
            }
            CharData elemental = Database.CreateMobile(Database.GetMobTemplate(indexNumber));

            elemental.AddToRoom(ch.InRoom);

            elemental.SetCoins(0, 0, 0, 0);
            elemental.Level        = 27 + MUDMath.Dice(2, 5);
            elemental.MaxHitpoints = 150 + MUDMath.Dice(16, level / 2);
            elemental.Hitpoints    = elemental.MaxHitpoints;
            elemental.ArmorPoints -= (ch.Level * 3 / 2);
            elemental.SetActionBit(MobTemplate.ACT_NOEXP);

            switch (indexNumber)
            {
            case StaticMobs.MOB_NUMBER_EARTH_PECH:
                SocketConnection.Act("$n&n rises from the ground before your eyes.", elemental,
                                     null, null, SocketConnection.MessageTarget.room);
                break;

            case StaticMobs.MOB_NUMBER_AIR_SLYPH:
                elemental.ArmorPoints = -130;
                elemental.PermAgility = 100;
                SocketConnection.Act("$n&n appears out of thin air.", elemental, null, null, SocketConnection.MessageTarget.room);
                break;

            case StaticMobs.MOB_NUMBER_FIRE_SERPENT:
                SocketConnection.Act("$n&n bursts into existence in a roaring ball of flame.",
                                     elemental, null, null, SocketConnection.MessageTarget.room);
                break;

            case StaticMobs.MOB_NUMBER_WATER_NEREID:
                SocketConnection.Act("$n&n coalesces into existence.", elemental, null, null, SocketConnection.MessageTarget.room);
                elemental.MaxHitpoints += 100;
                elemental.Hitpoints     = elemental.MaxHitpoints;
                break;

            default:
                Log.Error("SummonElem: bad indexNumber in switch: " + indexNumber);
                ch.SendText("You managed to summon a bad indexNumber! Shame on you.\r\n");
                break;
            }
            SocketConnection.Act("$N&n says 'Your wish is my command $n&n.'", ch, null, elemental, SocketConnection.MessageTarget.room);
            SocketConnection.Act("$N&n tells you 'Your wish is my command.'", ch, null, elemental, SocketConnection.MessageTarget.character);
            CharData.AddFollower(elemental, ch);
            elemental.Master = ch;
            Affect af = new Affect(Affect.AffectType.spell, spell.Name, level / 2 + MUDMath.Dice(4, level / 2), Affect.Apply.none, 0, Affect.AFFECT_CHARM);

            elemental.AddAffect(af);
            // Set the MobIndex.ACT_PET bit as well
            elemental.SetActionBit(MobTemplate.ACT_PET);
            elemental.FlightLevel = ch.FlightLevel;
            if (ch.Fighting)
            {
                Combat.SetFighting(elemental, ch.Fighting);
            }

            return;
        }
 public abstract Task <Response> ExecuteAsync(SocketConnection connection);
示例#19
0
 protected virtual bool BtcTurkHandleQueryResponse <T>(SocketConnection s, object request, JToken data, out CallResult <T> callResult)
 {
     // out params
     callResult = new CallResult <T>(default, null);
示例#20
0
        /// <summary>
        /// Reads line by line from the asterisk server, sets the protocol identifier as soon as it is
        /// received and dispatches the received events and responses via the associated dispatcher.
        /// </summary>
        /// <seealso cref="ManagerConnection.DispatchEvent(ManagerEvent)" />
        /// <seealso cref="ManagerConnection.DispatchResponse(Response.ManagerResponse)" />
        /// <seealso cref="ManagerConnection.setProtocolIdentifier(String)" />
        internal void  Run()
        {
            if (mrSocket == null)
            {
                throw new SystemException("Unable to run: socket is null.");
            }

            string line;

            while (true)
            {
                try
                {
                    while (!die)
                    {
                        #region check line from *
                        if (!is_logoff)
                        {
                            if (mrSocket != null && mrSocket.Initial)
                            {
                                Reinitialize();
                            }
                            else if (disconnect)
                            {
                                disconnect = false;
                                mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
                            }
                        }
                        if (lineQueue.Count == 0)
                        {
                            if (mrConnector.PingInterval > 0 &&
                                mrSocket != null &&
                                !wait4identiier &&
                                !is_logoff &&
                                lastPacketTime.AddMilliseconds(mrConnector.PingInterval) < DateTime.Now
                                )
                            {
                                if (pingHandler != null)
                                {
                                    // In 1.6.0 no Response from Ping
                                    if (pingHandler.Response == null)
                                    {
                                        // If one PingInterval from Ping without Pong then send Disconnect event
                                        mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
                                    }
                                    pingHandler.Free();
                                    mrConnector.RemoveResponseHandler(pingHandler);
                                    pingHandler = null;
                                }
                                else
                                {
                                    // Send PING to *
                                    try
                                    {
                                        pingHandler = new ResponseHandler(new Action.PingAction(), null);
                                        mrConnector.SendAction(pingHandler.Action, pingHandler);
                                    }
                                    catch
                                    {
                                        disconnect = true;
                                        mrSocket   = null;
                                    }
                                }
                                lastPacketTime = DateTime.Now;
                            }
                            Thread.Sleep(50);
                            if (mrConnector.TraceCallerThread && mrConnector.CallerThread != null && mrConnector.CallerThread.ThreadState == ThreadState.Stopped)
                            {
                                die = true;
                                break;
                            }
                            continue;
                        }
                        #endregion

                        lastPacketTime = DateTime.Now;
                        lock (((ICollection)lineQueue).SyncRoot)
                            line = lineQueue.Dequeue().Trim();
#if LOGGER
                        logger.Debug(line);
#endif
                        #region processing Response: Follows
                        if (processingCommandResult)
                        {
                            if (line == "--END COMMAND--")
                            {
                                Response.CommandResponse commandResponse = new Response.CommandResponse();
                                Helper.SetAttributes(commandResponse, packet);
                                commandResponse.Result  = commandList;
                                processingCommandResult = false;
                                packet.Clear();
                                mrConnector.DispatchResponse(commandResponse);
                                continue;
                            }
                            else
                            {
                                string lineLower = line.ToLower(Helper.CultureInfo);
                                if (lineLower.StartsWith("privilege: ") ||
                                    lineLower.StartsWith("actionid: ") ||
                                    lineLower.StartsWith("timestamp: ") ||
                                    lineLower.StartsWith("server: ")
                                    )
                                {
                                    Helper.AddKeyValue(packet, line);
                                }
                                else
                                {
                                    commandList.Add(line);
                                }
                            }
                            continue;
                        }
                        #endregion

                        #region collect key: value and ProtocolIdentifier
                        if (!string.IsNullOrEmpty(line))
                        {
                            if (wait4identiier && line.StartsWith("Asterisk Call Manager"))
                            {
                                wait4identiier = false;
                                ConnectEvent connectEvent = new ConnectEvent(mrConnector);
                                connectEvent.ProtocolIdentifier = line;
                                mrConnector.DispatchEvent(connectEvent);
                                continue;
                            }
                            if (line.Trim().ToLower(Helper.CultureInfo) == "response: follows")
                            {
                                // Switch to wait "--END COMMAND--" mode
                                processingCommandResult = true;
                                packet.Clear();
                                commandList.Clear();
                                Helper.AddKeyValue(packet, line);
                                continue;
                            }
                            Helper.AddKeyValue(packet, line);
                            continue;
                        }
                        #endregion

                        #region process events and responses

                        if (packet.ContainsKey("event"))
                        {
                            mrConnector.DispatchEvent(packet);
                        }

                        else if (packet.ContainsKey("response"))
                        {
                            mrConnector.DispatchResponse(packet);
                        }

                        #endregion

                        packet.Clear();
                    }
                    if (mrSocket != null)
                    {
                        mrSocket.Close();
                    }
                    break;
                }
#if LOGGER
                catch (Exception ex)
                {
                    logger.Info("Exception : {0}", ex.Message);
#else
                catch
                {
#endif
                }

                if (die)
                {
                    break;
                }

#if LOGGER
                logger.Info("No die, any error - send disconnect.");
#endif
                mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
            }
        }
示例#21
0
 protected override Task <bool> Unsubscribe(SocketConnection connection, SocketSubscription s)
 {
     throw new NotImplementedException();
 }
示例#22
0
        /// <summary>
        /// Async Read callback
        /// </summary>
        /// <param name="ar">IAsyncResult</param>
        private void mrReaderCallbback(IAsyncResult ar)
        {
            // mreader = Mr.Reader
            ManagerReader mrReader = (ManagerReader)ar.AsyncState;

            if (mrReader.die)
            {
                return;
            }

            SocketConnection mrSocket = mrReader.mrSocket;

            if (mrSocket == null || mrSocket.TcpClient == null)
            {
                // No socket - it's DISCONNECT !!!
                disconnect = true;
                return;
            }

            NetworkStream nstream = mrSocket.NetworkStream;

            if (nstream == null)
            {
                // No network stream - it's DISCONNECT !!!
                disconnect = true;
                return;
            }

            try
            {
                int count = nstream.EndRead(ar);
                if (count == 0)
                {
                    // No received data - it's may be DISCONNECT !!!
                    if (!is_logoff)
                    {
                        disconnect = true;
                    }
                    return;
                }
                string line = mrSocket.Encoding.GetString(mrReader.lineBytes, 0, count);
                mrReader.lineBuffer += line;
                int idx;
                // \n - because not all dev in Digium use \r\n
                // .Trim() kill \r
                lock (((ICollection)lineQueue).SyncRoot)
                    while (!string.IsNullOrEmpty(mrReader.lineBuffer) && (idx = mrReader.lineBuffer.IndexOf("\n")) >= 0)
                    {
                        line = idx > 0 ? mrReader.lineBuffer.Substring(0, idx).Trim() : string.Empty;
                        mrReader.lineBuffer = (idx + 1 < mrReader.lineBuffer.Length ? mrReader.lineBuffer.Substring(idx + 1) : string.Empty);
                        lineQueue.Enqueue(line);
                    }
                // Give a next portion !!!
                nstream.BeginRead(mrReader.lineBytes, 0, mrReader.lineBytes.Length, mrReaderCallbback, mrReader);
            }
#if LOGGER
            catch (Exception ex)
            {
                mrReader.logger.Error("Read data error", ex.Message);
#else
            catch
            {
#endif
                // Any catch - disconncatch !
                disconnect = true;
                if (mrReader.mrSocket != null)
                {
                    mrReader.mrSocket.Close();
                }
                mrReader.mrSocket = null;
            }
        }
示例#23
0
 /// <inheritdoc />
 protected override bool HandleQueryResponse <T>(SocketConnection s, object request, JToken data, out CallResult <T> callResult)
 {
     throw new NotImplementedException();
 }
 private void Awake()
 {
     GameConsole.Log("awake");
     _Connection = new SocketConnection(IP, Port, this);
     GameConsole.Log("awake2");
 }
示例#25
0
 /// <inheritdoc />
 protected override Task <CallResult <bool> > AuthenticateSocket(SocketConnection s)
 {
     throw new NotImplementedException();
 }
示例#26
0
 /// <inheritdoc />
 protected override bool HandleQueryResponse <T>(SocketConnection s, object request, JToken data, out CallResult <T> callResult)
 {
     callResult = new CallResult <T>(default, null);
示例#27
0
 public static void ConnectionRead(SocketConnection connection, int count)
 {
     // Don't log for now since this could be *too* verbose.
     // Reserved: Event ID 3
 }
示例#28
0
 public AuthenServerAdapter()
 {
     SocketConnection.Subscribe(EventNames.ORDER_MESSAGE, OnReceiveAuthen);
     SocketConnection.Subscribe(EventNames.INVENTORY_RSPD, OnReceiveInventoryAuthen);
 }
 protected virtual bool ParibuHandleQueryResponse <T>(SocketConnection s, object request, JToken data, out CallResult <T> callResult)
 {
     callResult = new CallResult <T>(default, null);
示例#30
0
 protected override TcpClientChannel <ReadOnlySequence <byte> > CreateChannel(SocketConnection connection, EndPoint address) => new SizedChannel(this, connection, address);
示例#31
0
		public Processor(SocketConnection socketConnection)
			: base(socketConnection)
		{
			//this.DataReceived += new ReceiveData(Processor_DataReceived);
			//this.ExceptionEncountered += new RaiseException(Processor_ExceptionEncountered);

			//// Development only - purely test Transaction processing with Commidea
			//if (ConfigurationSettings.AppSettings.Get("SkipBasketSteps") != null)
			//{
			//    mblnSkipBasketSteps = bool.Parse(ConfigurationSettings.AppSettings.Get("SkipBasketSteps"));
			//}
		}
示例#32
0
 public SizedChannel(TcpClient <ReadOnlySequence <byte> > client, SocketConnection connection, EndPoint address) : base(client, connection, address)
 {
 }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach(KeyValuePair<int, Connection> p in mConnections) {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MAEvent_type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MAConnEventData_handle, handle);
                evt.WriteInt32(MAConnEventData_opType, connOp);
                evt.WriteInt32(MAConnEventData_result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                Uri uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return MoSync.Constants.CONNERR_GENERIC;
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                Connection c = mConnections[_conn];
                return c.getAddr(_addr);
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                CommDelegate cd)
            {
                Connection c = mConnections[_conn];
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory mem = (Memory)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                cd(c, mem.GetData(),
                    delegate(int handle, int connOp, int result)
                    {
                        runtime.SetResourceRaw(_data, res);
                        mResultHandler(handle, connOp, result);
                    });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                    delegate(Connection c, byte[] buf, ResultHandler rh)
                    {
                        c.recv(buf, _offset, _size, rh);
                    });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                    delegate(Connection c, byte[] buf, ResultHandler rh)
                    {
                        c.write(buf, _offset, _size, rh);
                    });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return mNextConnHandle++;
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                c.setRequestHeader(key, value);
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
示例#34
0
		public SocketClient(SocketConnection socketConnection) 
		{
			Initialise(socketConnection.IPAddress,socketConnection.PortNo);
		}