Exemplo n.º 1
0
        public async Task AwaitFlowControl()
        {
            SendBytes sb = SendBytes;

            sb.Bytes = ToSend.Prepend((byte)NumberType).ToArray();
            await sb.AwaitFlowControl();
        }
Exemplo n.º 2
0
 private bool logIn(CommandLogin cmd)
 {
     try
     {
         Console.WriteLine("CH *new*: logging in...");
         Console.WriteLine("CH *new*: Login: {0} Pass: {1}", cmd.User, cmd.Pass);
         if (authenticate(cmd.User, cmd.Pass))
         {
             ID = cmd.User;
             Console.WriteLine("CH " + ID + ": Login successful");
             Command ctmp = new CommandAccept();
             ToSend.Add(ctmp);
             return(true);
         }
         else
         {
             Console.WriteLine("CH *new*: Invalid login or password. Login failed");
             Command ctmp = new CommandError(402);
             ToSend.Add(ctmp);
             Thread.Sleep(3000);
             cts.Cancel();
             return(false);
         }
     }
     catch (Exception)
     {
         Console.WriteLine("CH *new*: Login failed");
         cts.Cancel();
         return(false);
     }
 }
Exemplo n.º 3
0
        public async Task AwaitFlowControl()
        {
            string     send = ToSend.ToString();
            SendString ss   = SendString;

            ss.ToSend = send;
            await ss.AwaitFlowControl();
        }
Exemplo n.º 4
0
    // Lives in a thread!
    public void WriteMessages()
    {
        CheckersMessage nextMessage;

        while (Client.Connected)
        {
            // spin until there's a message to send
            while (!ToSend.TryDequeue(out nextMessage))
            {
                Thread.Sleep(100);
            }
            if (Client.Connected)              // could have disconnected in the interim between waiting for a message
            {
                Google.Protobuf.MessageExtensions.WriteDelimitedTo(nextMessage, Client.GetStream());
            }
        }
    }
Exemplo n.º 5
0
        private void frmSMPChat_Load(object sender, EventArgs e)
        {
            tmr          = new Timer();
            tmr.Interval = 50;
            DateTime last = DateTime.Now;

            tmr.Tick += delegate(object s, EventArgs a)
            {
                double msago = (DateTime.Now - last).TotalMilliseconds;
                if (ToSend.Count > 0 && msago > 1000)
                {
                    string first = ToSend.First.Value;
                    ToSend.RemoveFirst();
                    SendAction.Invoke(first);
                    last = DateTime.Now;
                }
                else if (ToSend.Count == 0)
                {
                    tmr.Enabled = false;
                }
            };
        }
Exemplo n.º 6
0
        public async Task GetRendomGift(decimal price, int userId)
        {
            var actualPrice = price - price * 5 / 100;
            var someGift    = (from gift in _unitOfWorks.Gift.List
                               where gift.Price <= actualPrice
                               select gift).ToList();
            Random r           = new Random();
            int    index       = r.Next(0, someGift.Count - 1);
            var    choosenGift = someGift[index];
            var    sendTo      = (from us in _unitOfWorks.Users.List
                                  where !us.Deleted && us.Id != userId
                                  select us).OrderByDescending(x => x.Rating).FirstOrDefault();


            ToSend sentobj = new ToSend
            {
                DestinationId = sendTo.Id,
                SourceId      = userId,
                GiftId        = choosenGift.Id,
                IsSending     = true
            };

            await _unitOfWorks.ToSends.Add(sentobj);
        }
Exemplo n.º 7
0
		// Will hold the buffers until they are sent
		public static void ScheduleSend(LaneSetup setup, DateTime now, ToSend[] tosend, uint count)
		{
			for (uint i=0;i<count;i++)
			{
				Lane lane = tosend[i].Lane;

				if (!tosend[i].Reliable)
				{
					uint target = (uint)lane.Out.Length;
					if (lane.OutCount == lane.Out.Length)
					{
						for (uint k=0;k<lane.Out.Length;k++)
						{
							if (lane.Out[k].Source == null)
							{
								target = k;
								break;
							}
						}
					}
					else
					{
						target = lane.OutCount++;
					}

					if (target == lane.Out.Length)
					{
						// Dropped
						continue;
					}

					if (tosend[i].CanKeepData)
					{
						lane.Out[target].Source = tosend[i].Data;
					}
					else
					{
						lane.Out[target].Source = setup.Factory.GetBuffer(tosend[i].Data.bytesize);
						Bitstream.Insert(lane.Out[target].Source, tosend[i].Data);
						Bitstream.SyncByte(lane.Out[target].Source);
						lane.Out[target].Source.Flip();
					}

					lane.Out[target].Source.userdata = 1; // refcount

					lane.Out[target].Begin = 0;
					lane.Out[target].End = tosend[i].Data.bytesize;
					lane.Out[target].IsFinalPiece = true;
					lane.Out[target].SendTime = now;
					lane.Out[target].InitialSendTime = now;
					lane.Out[target].SendCount = 0;
					lane.Out[target].SeqId = ++lane.OutgoingSeqUnreliable;
					lane.Out[target].Reliable = false;
				}
				else
				{
					uint segmentSize = setup.MaxPacketSize - 32 - setup.ReservedHeaderBytes;
					uint numSegments = (uint)(((tosend[i].Data.bytesize - tosend[i].Data.bytepos) + segmentSize - 1) / segmentSize);
					uint[] outSlots = new uint[256];
					if (numSegments == 0 || numSegments > outSlots.Length)
					{
						continue;
					}

					uint write = 0;
					for (uint k=0;k<lane.OutCount;k++)
					{
						if (lane.Out[k].Source == null)
						{
							outSlots[write++] = k;
							if (write == numSegments)
							{
								break;
							}
						}
					}

					uint left = numSegments - write;
					if ((lane.Out.Length - lane.OutCount) < left)
					{
						// no room.
						continue;
					}

					for (uint k=0;k<left;k++)
					{
						outSlots[write++] = lane.OutCount++;
					}

					Bitstream.Buffer source = tosend[i].Data;
					if (!tosend[i].CanKeepData)
					{
						source = setup.Factory.GetBuffer(tosend[i].Data.bytesize);
						Bitstream.Insert(source, tosend[i].Data);
						source.Flip();
					}

					source.userdata = 0;
					uint RangeBegin = 0;
					for (uint k=0;k<numSegments;k++)
					{
						uint bytesLeft = source.bytesize - RangeBegin;
						if (bytesLeft == 0)
						{
							Console.WriteLine("ERROR: bytesLeft=0!");
							continue;
						}
						uint toWrite = bytesLeft < segmentSize ? bytesLeft : segmentSize;
						uint slot = outSlots[k];
						source.userdata++;
						lane.Out[slot].Source = source;
						lane.Out[slot].Begin = RangeBegin;
						lane.Out[slot].End = RangeBegin + toWrite;
						lane.Out[slot].IsFinalPiece = k == (numSegments-1);
						lane.Out[slot].SendTime = now;
						lane.Out[slot].InitialSendTime = now;
						lane.Out[slot].SendCount = 0;
						lane.Out[slot].Reliable = true;
						lane.Out[slot].SeqId = ++lane.OutgoingSeqReliable;
						RangeBegin = RangeBegin + toWrite;
					}
				}
			}
		}
Exemplo n.º 8
0
        public override void Tick()
        {
            if (tdisco)
            {
                return;
            }
            if (!IsValid)
            {
                return;
            }
            int pc = PacketsToApply.Count;

            for (int i = 0; i < pc; i++)
            {
                PacketsToApply[i].Apply();
            }
            PacketsToApply.RemoveRange(0, pc);
            TickMovement(InWorld.Delta);
            // Manage Selection
            Location forward = Utilities.ForwardVector_Deg(Direction.X, Direction.Y);
            Location eye     = Position + new Location(0, 0, Maxes.Z);
            Location seltarg = eye + forward * 10;

            SelectedBlock = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, -1);
            if (SelectedBlock == seltarg)
            {
                SelectedBlock = Location.NaN;
            }
            // Break
            if (Attack && !SelectedBlock.IsNaN())
            {
                if (ServerMain.GlobalTickTime - 0.5 >= LastBreak)
                {
                    LastBreak = ServerMain.GlobalTickTime;
                    Location sel_block = SelectedBlock.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != 0)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)Material.AIR);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Attack)
            {
                LastBreak = 0;
            }
            // Place
            Item HeldItem = GetItemForSlot(QuickBarPos);

            if (Secondary && HeldItem.Material != Material.AIR)
            {
                if (ServerMain.GlobalTickTime - 0.3 >= LastPlace)
                {
                    Location back_a_block = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, 1);
                    LastPlace = ServerMain.GlobalTickTime;
                    Location sel_block = back_a_block.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != (ushort)HeldItem.Material)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)HeldItem.Material);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Secondary)
            {
                LastPlace = 0;
            }
            // TODO: Better tracking of what chunks to send
            List <Location> locs = GetChunksNear(World.GetChunkLocation(Position));

            foreach (Location loc in locs)
            {
                if (!ChunksAware.Contains(loc))
                {
                    ToSend.Add(loc);
                    ChunksAware.Add(loc);
                }
            }
            for (int i = 0; i < ChunksAware.Count; i++)
            {
                if (!locs.Contains(ChunksAware[i]))
                {
                    ToSend.Remove(ChunksAware[i]);
                    ChunksAware.RemoveAt(i--);
                }
            }
            sendtimer += InWorld.Delta;
            if (sendtimer >= 0.05f)
            {
                sendtimer = 0.05f;
                if (ToSend.Count > 0)
                {
                    Chunk ch = InWorld.LoadChunk(ToSend[0]);
                    SendToSecondary(new ChunkPacketOut(ch));
                    for (int i = 0; i < ch.Entities.Count; i++)
                    {
                        if (ch.Entities[i] != this)
                        {
                            Send(new NewEntityPacketOut(ch.Entities[i]));
                        }
                    }
                    ToSend.RemoveAt(0);
                }
            }
            // Handle networking
            lock (Packets)
            {
                for (int i = 0; i < Packets.Count; i++)
                {
                    try
                    {
                        Packets[i].Apply();
                    }
                    catch (Exception ex)
                    {
                        SysConsole.Output(OutputType.ERROR, "Networking / player / receive "
                                          + (Packets[i].IsChunkConnection ? "C-" : "") + "packet: " + ex.ToString());
                        Kick("Invalid packet " + Packets[i].GetType().Name); // TODO: Less internal-ish packet ID handling?
                    }
                }
                Packets.Clear();
            }
        }
Exemplo n.º 9
0
 public void SendMessage(CheckersMessage message)
 {
     ToSend.Enqueue(message);
 }
        public void ApplyTeleportEffects(Player Ply, List <string> Effects)
        {
            if (Ply == null)
            {
                return;
            }
            if (Effects.Count == 0)
            {
                return;
            }

            foreach (string effect in Effects)
            {
                string[] args = effect.Split((":").ToCharArray());
                switch (args.First().ToLower())
                {
                case "addahp":
                    if (Ply.Role == RoleType.Scp096)
                    {
                        continue;
                    }
                    try
                    {
                        Ply.AdrenalineHealth += Convert.ToInt32(args.ElementAt(1));
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "applyeffect":
                    try
                    {
                        Ply.ReferenceHub.playerEffectsController.EnableByString(args.ElementAt(1), Convert.ToInt32(args.ElementAt(2)));
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "broadcast":
                    try
                    {
                        int    type = Convert.ToInt32(args.ElementAt(1));
                        int    dur  = Convert.ToInt32(args.ElementAt(2));
                        string msg  = string.Join(" ", args.Skip(3));
                        IEnumerable <Player> Plrs = new List <Player> {
                        };
                        switch (type)
                        {
                        case 0:
                            Plrs = new List <Player> {
                                Ply
                            };
                            break;

                        case 1:
                            Plrs = Player.List;
                            break;

                        case 2:
                            Plrs = Player.List.Where(p => p.Team == Team.SCP);
                            break;

                        case 3:
                            Plrs = Player.List.Where(p => CommandProcessor.CheckPermissions(p.Sender, "AdminChat", PlayerPermissions.AdminChat));
                            break;

                        default:
                            Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" first argument (type) is invalid.");
                            break;
                        }
                        foreach (Player ToSend in Plrs)
                        {
                            ToSend.ClearBroadcasts();
                            ToSend.Broadcast((ushort)dur, msg.Replace("{Name}", Ply.Nickname).Replace("{Room}", GetRoomName(Ply.CurrentRoom)).Replace("{Class}", $"<color={Ply.Role.GetColor().ToHex()}>{Constants.ClassStrings[Ply.Role.ToString()]}</color>") + "\n");
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "damage":
                    try
                    {
                        int amt = Convert.ToInt32(args.ElementAt(1));
                        if (Ply.IsGodModeEnabled == false)
                        {
                            Ply.Hurt(amt, DamageTypes.Wall, "SCP-914 Teleportation");
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "dropitems":
                    try
                    {
                        if (args.ElementAt(1) == "all" || args.ElementAt(1) == "*")
                        {
                            Ply.Inventory.ServerDropAll();
                        }
                        else
                        {
                            int amount = Convert.ToInt32(args.ElementAt(1));
                            for (int i = 0; i < amount; i++)
                            {
                                int pos = rnd.Next(0, Ply.Inventory.items.Count() - 1);
                                Ply.DropItem(Ply.Inventory.items.ElementAt(pos));
                            }
                            ;
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "god":
                    try
                    {
                        if (!Ply.IsGodModeEnabled)     // do not toggle godmode if they already had it on - that defeats the point
                        {
                            Ply.IsGodModeEnabled = true;
                            Timing.CallDelayed((float)Convert.ToInt32(args.ElementAt(1)), () =>
                            {
                                Ply.IsGodModeEnabled = false;
                            });
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "stamina":
                    if (Ply.Team == Team.SCP)
                    {
                        break;
                    }
                    try
                    {
                        int amt = Convert.ToInt32(args.ElementAt(1)) / 100;
                        Ply.Stamina.RemainingStamina = amt;
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                default:
                    Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. Invalid effect type: {effect}.");
                    break;
                }
            }
        }
Exemplo n.º 11
0
 public void SendMessage(CheckersMessage message)
 {
     Debugging.Print("Sending message " + message.ToString());
     ToSend.Enqueue(message);
 }