Esempio n. 1
0
        public static int WriteRowOfTiles(ref Packet data, World world, int x, int y, ushort width)
        {
            data.Add((ushort)x, (ushort)y, width);
            var j = x;

            for (var t = 0; t < width; t++)
            {
                if (j >= (world.Width - 1))
                {
                    break;
                }
                ushort rle = 0;
                for (var k = (j + 1); k < (world.Width - 1); k++)
                {
                    if (!world.Tiles[k, y].CanRLE(world.Tiles[j, y]))
                    {
                        break;
                    }
                    rle++;
                }
                data.Add(world.Tiles[j, y].ForeID, world.Tiles[j, y].BackID, world.Tiles[j, y].ForeStyle, rle);
                j += (rle + 1);
            }
            return(j);
        }
Esempio n. 2
0
        private InlineProcessingResult TransportSetTimeouts(Packet request, Packet response)
        {
            var tlvs = default(List <Tlv>);

            if (request.Tlvs.TryGetValue(TlvType.TransSessExp, out tlvs) && tlvs.Count > 0)
            {
                this.Session.Expiry = DateTime.UtcNow.AddSeconds(tlvs[0].ValueAsDword());
            }

            if (request.Tlvs.TryGetValue(TlvType.TransCommTimeout, out tlvs) && tlvs.Count > 0)
            {
                this.currentTransport.Config.CommsTimeout = tlvs[0].ValueAsDword();
            }

            if (request.Tlvs.TryGetValue(TlvType.TransRetryTotal, out tlvs) && tlvs.Count > 0)
            {
                this.currentTransport.Config.RetryTotal = tlvs[0].ValueAsDword();
            }

            if (request.Tlvs.TryGetValue(TlvType.TransRetryWait, out tlvs) && tlvs.Count > 0)
            {
                this.currentTransport.Config.RetryWait = tlvs[0].ValueAsDword();
            }

            response.Add(TlvType.TransSessExp, (uint)(this.Session.Expiry - DateTime.UtcNow).TotalSeconds);
            response.Add(TlvType.TransCommTimeout, this.currentTransport.Config.CommsTimeout);
            response.Add(TlvType.TransRetryTotal, this.currentTransport.Config.RetryTotal);
            response.Add(TlvType.TransRetryWait, this.currentTransport.Config.RetryWait);

            response.Result = PacketResult.Success;

            return(InlineProcessingResult.Continue);
        }
Esempio n. 3
0
        /// <summary>
        /// Delete a character
        /// </summary>
        /// <param name="dp">Incoming packet</param>
        public void OnDeleteCharacter(DataPacket dp)
        {
            Int32  _id            = dp.Read <Int32>(); // Character id
            String passwordbefore = dp.Read <String>();

            if (passwordbefore != "111111")
            {
                // Send delete error
                Packet _packet = new Packet(Header.DELETEPLAYERRESULT);
                _packet.Add <Int32>((Int32)Error.ERR_PASSWORD);
                _packet.Add <Int32>((Int32)_id);
                _packet.Add <Int32>((Int32)0);
                this.Send(_packet);
                return;
            }
            foreach (Character _character in this.Characters)
            {
                if (_character.Id == _id)
                {
                    SQL.ExecuteQuery(Query.DELETE_CHARACTER, this.User.AccountId, _id, new DateTime().GetDateTimeFromTimeStamp(0).ToString());
                    this.SendCharacterDelete(_character.Id);
                    this.LoadCharacterList();
                    foreach (Character _char in this.Characters)
                    {
                        this.SendCharacterData(_char);
                    }
                    break;
                }
            }
        }
Esempio n. 4
0
        static void Main()
        {
            BaseClient client = new BaseClient();                                                            //Create an instance of the client used to connect to the server

            client.Connect("127.0.0.1", 6789);                                                               //Connect to the server using the ip and port provided
            while (client.IsConnected())                                                                     //While we are connected to the server
            {
                Packet p1 = new Packet(10);                                                                  //Create an empty packet of type 10
                p1.Add(DateTime.Now.Ticks);                                                                  //Add to the packet a long, in this case the current time in Ticks
                p1.Add(2.3f);                                                                                //Add a float
                p1.Add(new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }); //Add a float
                p1.AddList(new List <Double>()
                {
                    10.1, 10.2, 10.3, 10.4
                });
                p1.AddList(new List <Single>()
                {
                    10.1f, 10.2f, 10.3f, 10.4f
                });
                client.SendPacket(p1);             //Send the packet over the connection (packet auto disposes when sent)

                Packet p2 = new Packet(11);        //Create an empty packet of type 10
                p2.Add(true);                      //Add to the packet a bool
                p2.Add("test cake");               //Add to the packet a string
                p2.Add(Guid.NewGuid());            //Add to the packet a GUID
                client.SendPacket(p2);             //Send the packet over the connection (packet auto disposes when sent)

                Thread.Sleep(20);                  //Wait for 20 ms before repeating
            }
            client.Disconnect();
        }
Esempio n. 5
0
        private void OutputReceived(object state)
        {
            var stream = (StreamReader)state;

            while (!this.process.HasExited && !stream.EndOfStream)
            {
                if (!this.interactive)
                {
                    this.interactiveSemaphore.WaitOne(500);
                }

                if (this.interactive)
                {
                    using (var buffer = new MemoryStream())
                    {
                        while (stream.Peek() != -1)
                        {
                            var c = stream.Read();
                            buffer.WriteByte((byte)c);
                        }

                        // write out a packet
                        var packet = new Packet("core_channel_write");
                        packet.Add(TlvType.ChannelId, this.ChannelId);
                        packet.Add(TlvType.ChannelData, buffer.ToArray());

                        this.ChannelManager.Dispatch(packet);
                    }
                }
            }
        }
Esempio n. 6
0
 public void Write(Packet writer)
 {
     writer.Add(id);
     writer.Add(name);
     writer.Add(color);
     writer.Add(category);
 }
Esempio n. 7
0
        /// <summary>
        /// Send character resume success
        /// </summary>
        public void SendCharacterResume()
        {
            Packet _packet = new Packet(Header.GETBACK_RESULT);

            _packet.Add <Int32>(1);
            _packet.Add <Int32>(1);
            this.Send(_packet);
        }
Esempio n. 8
0
        /// <summary>
        /// Send login success
        /// </summary>
        public void SendLoginSuccess()
        {
            Packet _packet = new Packet(Header.CERTIFYRESULT);

            _packet.Add <Int32>((Int32)Error.CERT_OK);
            _packet.Add <Int32>(0);
            _packet.Add <Boolean>(false);
            this.Send(_packet);
        }
Esempio n. 9
0
        /// <summary>
        /// Send the character delete result
        /// </summary>
        /// <param name="id"></param>
        public void SendCharacterDelete(Int32 id)
        {
            Packet _packet = new Packet(Header.DELETEPLAYERRESULT);

            _packet.Add <Int32>((Int32)Error.ERR_SUCCESS);
            _packet.Add <Int32>(id);
            _packet.Add <Int32>(2);
            this.Send(_packet);
        }
Esempio n. 10
0
        private static Tuple <string, Packet> ProcessPNG(string fileName)
        {
            Tuple <int, int, byte[], string> data = LoadPng(fileName);
            Packet p = new Packet(PACKETID_PNG);

            p.Add(data.Item1);
            p.Add(data.Item2);
            p.Add(data.Item3);
            return(new Tuple <string, Packet>(fileName.Replace(INPUTFOLDER + "\\", "").ToLower().Replace(".png", ".Gdat"), p));
        }
Esempio n. 11
0
    public static Packet    newPacket(int packet_id, params object[] list)
    {
        Packet packet = new Packet();

        packet.Add(packet_id);
        for (int i = 0; i < list.Length; i++)
        {
            packet.Add(list[i]);
        }
        return(packet);
    }
Esempio n. 12
0
        public void SendJoinRight()
        {
            Packet _packet = new Packet(Header.JOIN_RIGHT);

            _packet.Add <Int32>(this.Player.Id);
            _packet.Add <Int32>(this.Player.MapId);
            _packet.Add <Position>(this.Player.Position);
            _packet.Add <Boolean>(false); //Is festival
            _packet.Add <Int32>(0);       //Festival 'yday'
            this.Send(_packet);
        }
Esempio n. 13
0
        public static TcpServerChannel Create(Core.ChannelManager channelManager, Packet request, Packet response)
        {
            var localHost = request.Tlvs.TryGetTlvValueAsString(TlvType.StdapiLocalHost);
            var localPort = (int)request.Tlvs.TryGetTlvValueAsDword(TlvType.StdapiLocalPort);

            var channel = new TcpServerChannel(channelManager, localHost, localPort);

            response.Add(TlvType.StdapiLocalHost, channel.LocalHost);
            response.Add(TlvType.StdapiLocalPort, channel.LocalPort);

            return(channel);
        }
Esempio n. 14
0
 private static void CheckMotdPackets()
 {
     if (MOTDNonAdmin.bytes == null)
     {
         MOTDNonAdmin.Add(Packet.Types.MOTD);
         MOTDNonAdmin.Add(ServerSettings.Version);
         MOTDNonAdmin.Add(ServerSettings.GetSetting("ServerName"), 64);
         MOTDNonAdmin.Add(ServerSettings.GetSetting("motd"), 64);
         MOTDNonAdmin.Add((byte)0);
         MOTDAdmin            = MOTDNonAdmin;
         MOTDAdmin.bytes[130] = 100;
     }
 }
Esempio n. 15
0
        public Packet Serialize(Object o)
        {
            Packet returnPacket = new Packet(UInt16.MaxValue - 67);

            List <Tuple <Guid, Object> > objectsToSerialize = new List <Tuple <Guid, Object> > {
                new Tuple <Guid, Object>(Guid.NewGuid(), o)
            };
            Dictionary <Guid, Object> objectsSerialized = new Dictionary <Guid, Object>();

            while (objectsToSerialize.Count > 0)
            {
                (Guid item1, Object item2) = objectsToSerialize[objectsToSerialize.Count - 1];
                objectsToSerialize.RemoveAt(objectsToSerialize.Count - 1);
                if (item2 == null)
                {
                    continue;
                }

                if (objectsSerialized.ContainsValue(item2))
                {
                    // returnPacket.Add(objectsSerialized.FirstOrDefault(a => a.Value == objectBeingSerialized.Item2).Key);
                    continue;
                }

                objectsSerialized.Add(item1, item2);

                TypeContract typeContract = GetTypeContract(item2.GetType());

                returnPacket.Add(item1);
                returnPacket.Add(typeContract.UID);
                foreach (Tuple <String, PropertyInfo, Packet.ParamTypes> propertyType in typeContract.PropertyTypes)
                {
                    if (propertyType.Item3 == Packet.ParamTypes.AUTOPACK_REFERENCE)
                    {
                        Guid   guid = Guid.NewGuid();
                        Object deserializationTarget = propertyType.Item2.GetValue(item2);
                        if (deserializationTarget != null)
                        {
                            objectsToSerialize.Add(new Tuple <Guid, Object>(guid, deserializationTarget));
                        }
                        returnPacket.AddObject(guid);
                    }
                    else
                    {
                        returnPacket.AddObject(propertyType.Item2.GetValue(item2));
                    }
                }
            }
            return(returnPacket);
        }
Esempio n. 16
0
 public void Write(Packet writer)
 {
     writer.Add(id);
     writer.Add(character);
     writer.Add(template);
     writer.Add(title);
     writer.Add(description);
     writer.Add(canStack);
     writer.Add(number);
     writer.Add(Converter.FormatEffects(stats));
     writer.Add(slot);
 }
Esempio n. 17
0
        /// <summary>Parse a string into a packet structure</summary>
        public static Packet Parse(string packet)
        {
            if (packet[0] != DOLLAR)
            {
                throw new Exception("String is not a pakcet");
            }

            string[] args = packet.Split(DELIMIT, STAR);

            Packet p = new Packet(args[0].Substring(1));

            for (int i = 1; i < args.Length - 1; i++)
            {
                p.Add(args[i]);
            }

            byte crc = Convert.ToByte(args[args.Length - 1], 16);

            if (crc != p.CRC)
            {
                throw new Exception("Packet has incorrect checksum");
            }

            return(p);
        }
Esempio n. 18
0
        /// <summary>发送数据包到目的地址</summary>
        /// <param name="pk"></param>
        /// <param name="remote"></param>
        /// <param name="wait"></param>
        /// <returns></returns>
        internal async Task <Packet> SendAsync(Packet pk, IPEndPoint remote, Boolean wait)
        {
            if (pk.Count > 0)
            {
                if (remote != null && remote.Address == IPAddress.Broadcast && !Client.EnableBroadcast)
                {
                    Client.EnableBroadcast = true;
                    // 广播匹配任意响应
                    remote = null;
                }
            }

            if (Packet == null)
            {
                Packet = new PacketProvider();
            }

            var task = !wait ? null : Packet.Add(pk, remote, Timeout);

            // 这里先发送,基类的SendAsync注定发给Remote而不是remote
            if (!SendByQueue(pk, remote))
            {
                return(null);
            }

            if (!wait)
            {
                return(null);
            }

            return(await task.ConfigureAwait(false));
        }
Esempio n. 19
0
        /// <summary>
        /// Send that there is a version error between version send by client and version in server configuration
        /// </summary>
        public void SendVersionError(UInt32 realVersion)
        {
            Packet _packet = new Packet(Header.CERTIFYRESULT);

            _packet.Add <Int32>((Int32)(realVersion < Configuration.CurrentVersion ? Error.ERR_VERSION_TOO_LOW : Error.ERR_VERSION_MAINTAIN));
            this.Send(_packet);
        }
Esempio n. 20
0
        public virtual PacketResult Read(Packet request, Packet response)
        {
            var bytesToRead = request.Tlvs.TryGetTlvValueAsDword(TlvType.Length);
            var buffer      = new byte[bytesToRead];
            var bytesRead   = default(int);
            var result      = this.ReadInternal(buffer, out bytesRead);

            if (result == PacketResult.Success)
            {
                // TODO: handle channel flags/etc
                response.Add(TlvType.ChannelData, buffer, bytesRead);
                response.Add(TlvType.Length, bytesRead);
            }

            return(result);
        }
Esempio n. 21
0
 private InlineProcessingResult GetUid(Packet request, Packet response)
 {
     // TODO: validate that this works correctly when we impersonate other users or use `getsystem`
     response.Add(TlvType.StdapiUserName, WindowsIdentity.GetCurrent().Name);
     response.Result = PacketResult.Success;
     return(InlineProcessingResult.Continue);
 }
Esempio n. 22
0
        private InlineProcessingResult GetSysinfo(Packet request, Packet response)
        {
            response.Add(TlvType.StdapiComputerName, GetSystemMachineName());
            response.Add(TlvType.StdapiOperatingSystemName, GetOsVersionString());
            response.Add(TlvType.StdapiArchitecture, GetSystemArchitecture());
            response.Add(TlvType.StdapiLangSystem, GetSystemLocale());

            var domain = GetSystemDomainName();

            if (!string.IsNullOrEmpty(domain))
            {
                response.Add(TlvType.StdapiDomain, domain);
            }
            response.Result = PacketResult.Success;
            return(InlineProcessingResult.Continue);
        }
Esempio n. 23
0
        public Base GetCompletedWork(Guid jobGuid)
        {
            if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager");

            while (true)
            {
                Packet p = new Packet(1100);
                p.Add(jobGuid.ToByteArray(),true);
                _ConnectionToManager.SendPacket(p);
                Stopwatch sendTime = new Stopwatch();
                sendTime.Start();
                while (sendTime.ElapsedMilliseconds < _CommsTimeout)
                {
                    if (_ConnectionToManager.GetPacketsToProcessCount() > 0)
                    {
                        foreach (Packet packet in _ConnectionToManager.GetPacketsToProcess())
                        {
                            switch (packet.Type)
                            {
                                case 1101:
                                    return null;
                                case 1102:
                                    Object[] packetObjects = packet.GetObjects();
                                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                                    return (Base) binaryFormatter.Deserialize(new MemoryStream((Byte[]) packetObjects[0]));
                            }
                        }
                        Thread.Sleep(100);
                    }
                }
                if (_ConnectionToManager.IsConnected())_ConnectionToManager.Disconnect();
                _ConnectionToManager.Connect(_IpAddress, _Port, 204800);
            }
            return null;
        }
Esempio n. 24
0
        private InlineProcessingResult CoreLoadLib(Packet request, Packet response)
        {
            var data     = request.Tlvs[TlvType.Data].First().ValueAsRaw();
            var assembly = Assembly.Load(data);

            var pluginType = assembly.GetTypes().Where(t => t.IsClass && typeof(IPlugin).IsAssignableFrom(t)).FirstOrDefault();

            if (pluginType != null)
            {
                var pluginInstance = assembly.CreateInstance(pluginType.FullName) as IPlugin;
                pluginInstance.Register(this);

                foreach (var cmd in GetCommandsForExtension(pluginInstance.Name))
                {
                    response.Add(TlvType.Method, cmd);
                }

                response.Result = PacketResult.Success;
            }
            else
            {
                response.Result = PacketResult.InvalidData;
            }

            return(InlineProcessingResult.Continue);
        }
Esempio n. 25
0
File: NMEA.cs Progetto: fbstj/lib.cs
		/// <summary>Packet factory that adds multiple arguments to the pakcet</summary>
		public static Packet Raw(string command, params string[] args)
		{
			Packet p = new Packet(command);
			foreach (string arg in args)
				p.Add(arg);
			return Parse(p.ToString());
		}
Esempio n. 26
0
        /// <summary>
        /// Reponse au ping du client
        /// </summary>
        /// <param name="dp"></param>
        public void OnPing(DataPacket dp)
        {
            Packet pak = new Packet((Int16)10);

            pak.Add <UInt32>(dp.Read <UInt32>());
            this.Send(pak);
        }
Esempio n. 27
0
        /// <summary>
        /// Send the character creation result
        /// </summary>
        /// <param name="result">Result of the character creation</param>
        public void SendCharacterCreationResult(Error result)
        {
            Packet _packet = new Packet(Header.CREATEPLAYERRESULT);

            _packet.Add <Int32>((Int32)result);
            this.Send(_packet);
        }
Esempio n. 28
0
 private InlineProcessingResult ChannelRead(Packet request, Packet response)
 {
     return(ChannelAct(request, response, channel =>
     {
         response.Add(TlvType.ChannelId, channel.ChannelId);
         return channel.Read(request, response);
     }));
 }
 void OnOutgoingData(Player p, PacketEventArgs e)
 {
     if (e.Type == Packet.Types.MOTD)
     {
         string ip;
         if (Server.DebugMode)
         {
             ip = "127.0.0.1";
         }
         else
         {
             ip = InetUtils.GrabWebpage("http://www.mcforge.net/serverdata/ip.php");
         }
         Packet pa = new Packet();
         pa.Add(Packet.Types.MOTD);
         pa.Add((byte)7);
         pa.Add(ServerSettings.GetSetting("ServerName"), 64);
         pa.Add(ServerSettings.GetSetting("MOTD") + " &0cfg=" + ip + ":" + ServerSettings.GetSetting("Port") + "/" + p.Level.Name, 64);
         pa.Add((byte)0);
         e.Data = pa.bytes;
     }
     //Because this is way more fun and requires no edits to the core ~Gamemakergm
     else if (e.Type == Packet.Types.Message)
     {
         if (PluginSettings.GetSettingBoolean("joinleave-alert"))
         {
             string incoming = Encoding.ASCII.GetString(e.Data).Trim();
             //Logger.Log(incoming);
             if (incoming.Contains("joined the game!"))
             {
                 e.Cancel();
                 WOM.GlobalSendJoin(incoming.Substring(1, incoming.Length - incoming.IndexOf("joined the game!")));
             }
             else if (incoming.Contains("has disconnected"))
             {
                 e.Cancel();
                 WOM.GlobalSendLeave(incoming.Substring(1, incoming.Length - incoming.IndexOf("has disconnected")));
             }
         }
     }
     else
     {
         return;
     }
 }
Esempio n. 30
0
        private void ChannelClosed(object sender, EventArgs e)
        {
            var channel = (Channel)sender;
            var packet  = new Packet("core_channel_close");

            packet.Add(TlvType.ChannelId, channel.ChannelId);
            this.Dispatch(packet);
            this.activeChannels.Remove(channel.ChannelId);
        }
Esempio n. 31
0
        public void Use(Player p, string[] args)
        {
            System.Random r   = new System.Random();
            string        msg = "";

            while (p.IsLoggedIn)
            {
                Packet pp = new Packet();
                pp.Add((byte)5);
                ushort x = (ushort)r.Next(ushort.MaxValue), z = (ushort)r.Next(ushort.MaxValue), y = (ushort)r.Next(ushort.MaxValue);
                ushort a = (ushort)r.Next(ushort.MaxValue);
                pp.Add(x);
                pp.Add(z);
                pp.Add(y);
                pp.Add(a);
                p.SendPacket(pp);
                msg = "" + x + " " + z + " " + y + " " + pp.bytes[7] + " " + pp.bytes[8];
                p.SendMessage(msg);
                Logger.Log(msg);
                System.Threading.Thread.Sleep(100);
            }
            return;

            for (int i = 0; i < byte.MaxValue; i++)
            {
                Packet pa = new Packet();
                pa.Add((byte)5);
                //pa.Add((ushort)0); pa.Add((ushort)0); pa.Add((ushort)0);
                for (int a = 0; a < i; a++)
                {
                    pa.Add((byte)2);
                }
                for (int a = i; a < 255; a++)
                {
                    pa.Add((byte)1);
                }
                p.SendPacket(pa);
                msg = "" + i;
                p.SendMessage(msg);
                Logger.Log(msg);
                System.Threading.Thread.Sleep(500);
            }
            return;
        }
Esempio n. 32
0
        /// <summary>
        /// Serialize the inventory in packet
        /// </summary>
        /// <param name="packet">Outgoing packet</param>
        public void Serialize(Packet packet)
        {
            packet.Add <Byte>(this.MaxItem);
            packet.Add <Byte>((Byte)Define.MAX_INVENTORY);
            packet.Add <Byte[]>(InventorySlots);
            // TO DO :

            /*if self.m_index[i] >= 0 then
             * local elem = self.m_item[self.m_index[i]]
             * elem.m_objindex = i
             * elem.m_bag_id = self.m_bag_id
             * end*/
            packet.Add <Byte>((Byte)this.Items.Count);
            foreach (Item _item in this.Items)
            {
                _item.Serialize(packet);
                packet.Add <Byte>((byte)Array.IndexOf(InventorySlots, _item.Slot));
            }
        }
 /// <summary>
 ///     An instance of a client connection on the server
 /// </summary>
 /// <param name="newSocket"> </param>
 /// <param name="bufferSizeInKB">The buffer size in kb for incoming packets</param>
 protected ClientConnection(TcpClient newSocket, Int32 bufferSizeInKB = 1024)
 {
     _ByteBuffer = new Byte[bufferSizeInKB * 1024];
     _ClientId = GetNewClientId();
     _TimeOfConnection = DateTime.Now;
     _AttachedSocket = newSocket;
     _Connected = true;
     Packet p = new Packet(CONNECT_PACKET);
     p.Add(_ClientId);
     _PacketsToSend.Add(p);
     OnConnect();
     _UpdateThread = new Thread(Update);
     _UpdateThread.Start();
 }
        /// <summary>
        /// This is run on a seperate thread at a given interval, its useful for handeling incoming packets
        /// </summary>
        protected override void ClientUpdateLogic()
        {
            foreach (Packet packet in GetOutStandingProcessingPackets())
            {
                switch (packet.Type)
                {
                    case 10:
                        Program.Write(((Int64)packet.GetObjects()[0]).ToString(CultureInfo.InvariantCulture));
                        Program.Write(((Single)packet.GetObjects()[1]).ToString(CultureInfo.InvariantCulture));

                        Byte[] data = ((Byte[]) packet.GetObjects()[2]);
                        StringBuilder sb = new StringBuilder();
                        foreach (Byte b in data)
                        {
                            sb.Append(b);
                            sb.Append(',');
                        }
                        sb.AppendLine();

                        foreach (Double d in (List<Double>)packet.GetObjects()[3])
                        {
                            sb.Append(d);
                            sb.Append(',');
                        }


                            sb.AppendLine();

                            foreach (Single d in (List<Single>)packet.GetObjects()[4])
                        {
                            sb.Append(d);
                            sb.Append(',');
                        }

                        Program.Write(sb.ToString());

                        Packet response = new Packet(45);
                        response.Add(data);

                        SendPacket(response);
                        break;
                    case 11:
                        Program.Write(((Boolean)packet.GetObjects()[0]).ToString(CultureInfo.InvariantCulture));
                        Program.Write(((String)packet.GetObjects()[1]).ToString(CultureInfo.InvariantCulture));
                        Program.Write(((Guid)packet.GetObjects()[2]).ToString());
                        break;
                }
            }
        }
        static void Main()
        {
            BaseClient client = new BaseClient();   //Create an instance of the client used to connect to the server
            client.Connect("127.0.0.1", 6789);      //Connect to the server using the ip and port provided
            while (client.IsConnected())            //While we are connected to the server
            {
                Packet p1 = new Packet(10);         //Create an empty packet of type 10
                p1.Add(DateTime.Now.Ticks);         //Add to the packet a long, in this case the current time in Ticks
                p1.Add(2.3f);                       //Add a float
                p1.Add(new Byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19});                  //Add a float
                p1.AddList(new List<Double>() { 10.1, 10.2, 10.3, 10.4 });
                p1.AddList(new List<Single>() { 10.1f, 10.2f, 10.3f, 10.4f });
                client.SendPacket(p1);              //Send the packet over the connection (packet auto disposes when sent)

                Packet p2 = new Packet(11);         //Create an empty packet of type 10
                p2.Add(true);                       //Add to the packet a bool
                p2.Add("test cake");                //Add to the packet a string
                p2.Add(Guid.NewGuid());             //Add to the packet a GUID
                client.SendPacket(p2);              //Send the packet over the connection (packet auto disposes when sent)

                Thread.Sleep(20);                  //Wait for 20 ms before repeating
            }
            client.Disconnect();
        }
Esempio n. 36
0
File: NMEA.cs Progetto: fbstj/lib.cs
		/// <summary>Parse a string into a packet structure</summary>
		public static Packet Parse(string packet)
		{
			if (packet[0] != DOLLAR)
				throw new Exception("String is not a pakcet");

			string[] args = packet.Split(DELIMIT, STAR);

			Packet p = new Packet(args[0].Substring(1));

			for (int i = 1; i < args.Length - 1; i++)
				p.Add(args[i]);

			byte crc = Convert.ToByte(args[args.Length - 1], 16);

			if (crc != p.CRC)
				throw new Exception("Packet has incorrect checksum");

			return p;
		}
Esempio n. 37
0
        /// <summary>
        ///     Handels a packet of type 1000, this packet should be used to sent a work request
        /// </summary>
        /// <param name="p"></param>
        protected void HandelA1000(Packet p)
        {
            Object[] packetObjects = p.GetObjects();
            Guid jobGuid = Guid.NewGuid();
            Byte[] jobData = (Byte[])packetObjects[0];

            Base activity = null;
            try
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                activity = (Base) binaryFormatter.Deserialize(new MemoryStream(jobData));
                activity.SetGuid(jobGuid);

            Packet returnPacket = new Packet(1001);
            returnPacket.Add(jobGuid.ToByteArray(),true);
            SendPacket(returnPacket);
            Program.AddJob(activity);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 38
0
        private static Packet DemoAnimation()
        {
            var text = new TextFile('A') {
                new TextFileLine("<speed 5 /><picture 1/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 2/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 3/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 4/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 5/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 6/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 6/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 5/> <picture 3/> <picture 1/> <picture 2/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 4/> <picture 2/> <picture 1/> <picture 3/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 3/> <picture 1/> <picture 2/> <picture 4/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 2/> <picture 1/> <picture 3/> <picture 5/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 1/> <picture 2/> <picture 4/> <picture 6/>", DisplayMode.Hold),
            };

            var pic1 = new PictureFile('1', "kirby/frame1.png", ColorFormat.Monochrome);
            var pic2 = new PictureFile('2', "kirby/frame2.png", ColorFormat.Monochrome);
            var pic3 = new PictureFile('3', "kirby/frame3.png", ColorFormat.Monochrome);
            var pic4 = new PictureFile('4', "kirby/frame4.png", ColorFormat.Monochrome);
            var pic5 = new PictureFile('5', "kirby/frame5.png", ColorFormat.Monochrome);
            var pic6 = new PictureFile('6', "kirby/frame6.png", ColorFormat.Monochrome);

            var packet = new Packet();
            packet.SetMemory(new FileTable {
                text,
                pic1, pic2, pic3, pic4, pic5, pic6
            });
            packet.Add(new WriteTextCommand(text));
            packet.Add(new WritePictureCommand(pic1));
            packet.Add(new WritePictureCommand(pic2));
            packet.Add(new WritePictureCommand(pic3));
            packet.Add(new WritePictureCommand(pic4));
            packet.Add(new WritePictureCommand(pic5));
            packet.Add(new WritePictureCommand(pic6));

            return packet;
        }
Esempio n. 39
0
        private static void DemoStrings(IConnection conn)
        {
            var packet = new Packet();

            var text = new TextFile('A') {
                {"<string C/>", DisplayMode.Scroll}
            };

            packet.SetMemory(new FileTable {
                {'C', new StringFileInfo(10)},
                text
            });

            packet.Add(new WriteTextCommand(text));
            conn.Send(packet);

            for(int i = 0; i < 60; i++)
            {
                packet = new Packet();
                packet.Add(new WriteStringCommand(new StringFile('C', i.ToString("000"))));
                conn.Send(packet);
                Thread.Sleep(1000);
            }
        }
Esempio n. 40
0
 /// <summary>
 /// Reponse au ping du client
 /// </summary>
 /// <param name="dp"></param>
 public void OnPing(DataPacket dp)
 {
     Packet pak = new Packet((Int16)10);
     pak.Add<UInt32>(dp.Read<UInt32>());
     this.Send(pak);
 }
Esempio n. 41
0
        public Guid SendJob(Base activity)
        {
            if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager");

            while (true)
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                MemoryStream datastream = new MemoryStream();
                binaryFormatter.Serialize(datastream, activity);
                Packet p = new Packet(1000);
                Byte[] data= datastream.ToArray();
                p.Add(data,true);
                _ConnectionToManager.SendPacket(p);
                Stopwatch sendTime = new Stopwatch();
                sendTime.Start();
                while (sendTime.ElapsedMilliseconds < _CommsTimeout)
                {
                    if (_ConnectionToManager.GetPacketsToProcessCount() > 0)
                    {
                        foreach (Guid jobGuid in from packet in _ConnectionToManager.GetPacketsToProcess() where packet.Type == 1001 select new Guid((Byte[]) packet.GetObjects()[0]))
                        {

                            return jobGuid;
                        }
                    }
                    Thread.Sleep(1);
                }
                if (_ConnectionToManager.IsConnected()) _ConnectionToManager.Disconnect();
                _ConnectionToManager.Connect(_IpAddress, _Port, 20480 * 1024);
            }
            throw new Exception("Mananger unavailable or busy");
        }
Esempio n. 42
0
 public virtual Packet ToPacket()
 {
     Packet p = new Packet(PACKETIDENTIFIER);
     p.Add(_ActivityInstanceIdentifier.ToByteArray(),true);
     return p;
 }
Esempio n. 43
0
 /// <summary>
 /// Serialize the current Item in the packet
 /// </summary>
 /// <param name="packet"></param>
 public void Serialize(Packet packet)
 {
     packet.Add<Byte>(this.Slot); //m_objid
     packet.Add<Int32>(this.Id); //m_itemid
     packet.Add<UInt32>(0x00000000); //EC D9 14 91  (m_serial_number)
     packet.WriteX((Int32)this.Quantity); //m_item_num
     packet.WriteX(0); //CF 46 00 00  (Hitpoints => Current Durability?)
     packet.WriteX(0); //18 47 00 00  (Maximum Hitpoints => Maximum Durability?)
     packet.Add<UInt32>(0x00000000); //00 00 00 00  (Word => ?)
     packet.Add<Byte>(0x00); //00  (Ability Option => ?)
     packet.Add<Byte>(0x00); //00  (Item Resistance => ?)
     packet.Add<Byte>(0x00); //00  (Resistance Ability Option => ?)
     packet.WriteX(0x00000000); //00 00 00 00  (Keep Time)
     packet.Add<Byte>(0x00); //00  (Item Lock)
     packet.Add<Int32>(0x00000000); //00 00 00 00  (Bind End Time)
     packet.Add<Byte>(0x00); //00  (Stability => ?)
     packet.Add<Byte>(0x00); //00  (Quality => ?)
     packet.Add<Byte>(0x00); //00  (Ability Rate => ?)
     packet.WriteX(0); //00 00 00 00  (Use Time => ?)
     packet.WriteX(0); //00 00 00 00  (Buy 'tm' => Buy Time?)
     packet.WriteX(0); //00 00 00 00  (Price => Sell/Buy?)
     packet.WriteX(0); //00 00 00 00  (Pay 银币 => ?)
     packet.WriteX(0); //00 00 00 00  (Free 银币 => ?)
     packet.Add<UInt32>(Configuration.Get<UInt32>("ServerId"));
     packet.Add<Byte>(0); //Attributes  LAr:ReadVarArrayInt16(ar, self.m_attr)
 }
Esempio n. 44
0
 protected void HandelA1100(Packet p)
 {
     Object[] dataObjects = p.GetObjects();
     Guid jobLookupID = new Guid((Byte[])dataObjects[0]);
     Base activity = Program.GetCompletedJobByGuid(jobLookupID);
     if (activity == null) SendPacket(new Packet(1101));
     else
     {
         Packet returnPacket = new Packet(1102);
         BinaryFormatter binaryFormatter = new BinaryFormatter();
         MemoryStream datapackage = new MemoryStream();
         binaryFormatter.Serialize(datapackage, activity);
         returnPacket.Add(datapackage.ToArray(),true);
         SendPacket(returnPacket);
     }
 }
Esempio n. 45
0
 /// <summary>
 ///     Handels and incoming packet with ID 200, this is a hello packet from the lobe manager to which we repsond
 ///     with the number of worker threads we ahve running
 /// </summary>
 private void HandelA200Packet()
 {
     Packet responsePacket = new Packet(201);
     responsePacket.Add(_ActiveWorkerServices.Count);
     _ConnectionToLobeManager.SendPacket(responsePacket);
 }
Esempio n. 46
0
        /// <summary>
        ///     Handels a packet of type 300, This is a work request packet from the lobe worker, these will be recieved
        ///     regulary if the worker has no work at this stage. Having the workers poll the manager better fits the
        ///     parent child model and reliance pathways.
        /// </summary>
        /// <param name="p"></param>
        protected void HandelA300(Packet p)
        {
            Base work = Program.GetPendingJob();
            if (work == null) SendPacket(new Packet(301)); //got no work
            else
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                MemoryStream datapackage = new MemoryStream();
                binaryFormatter.Serialize(datapackage, work);

                Packet responsePacket = new Packet(302);
                responsePacket.Add(datapackage.ToArray(),true);
                SendPacket(responsePacket);
            }
        }
Esempio n. 47
0
        public void Start(Settings settings)
        {
            _Settings = settings;
            _CanRequestWork = true;
            AnnounceStatus("Lobe Worker Launching");
            _Running = true;
            _TimeOfLastManagerComms = DateTime.Now;
            _TargetThreads = _Settings.WorkerThreadCount;

            //Prepare the worker threads
            AnnounceStatus("Preparing Workers");
            for (Int32 i = 0; i < _TargetThreads; i++)
            {
                lock (_ActiveWorkerServices)
                {
                    _ActiveWorkerServices.Add(new WorkerThread(this));
                }
            }

            AnnounceStatus("Connecting To Manager");
            lock (_PacketsToBeProcessed)
            {
                if (!_ConnectionToLobeManager.Connect(_Settings.CommsManagerIp, _Settings.CommsManagerPort, 20480 * 1024)) AnnounceStatus("Unable to communicate with specified lobe manager, aborting!");
            }

            AnnounceStatus("Lobe Worker Online");
            while (_Running || _ActiveWorkerServices.Count > 0)
            {
                lock (this)
                {
                    _ActiveWorkerServices = _ActiveWorkerServices.Where(a => a.IsRunning()).ToList();
                    if (_CurrentThreads < _TargetThreads && _Running)
                    {
                        _ActiveWorkerServices.Add(new WorkerThread(this));
                    }
                    if (!_ConnectionToLobeManager.IsConnected())
                    {
                        String error = _ConnectionToLobeManager.GetError();
                        if (!string.IsNullOrEmpty(error)) Console.WriteLine("Net Error " + error);
                        AnnounceStatus("Unable to communicate with specified lobe manager, Attempting to reconnect");
                        if (_ConnectionToLobeManager.Connect(_Settings.CommsManagerIp, _Settings.CommsManagerPort, 20480 * 1024)) AnnounceStatus("Connection Re-established");
                        _CanRequestWork = true;
                    }
                    else
                    {
                        lock (_CompletedWork)
                        {
                            if (_CompletedWork.Count > 0)
                            {
                                using (Base job = _CompletedWork[0])
                                {
                                    _CompletedWork.RemoveAt(0);
                                    BinaryFormatter binaryFormatter = new BinaryFormatter();

                                    using (MemoryStream datapackage = new MemoryStream())
                                    {
                                        binaryFormatter.Serialize(datapackage, job);
                                        _CompletedJobs++;
                                        Packet responsePacket = new Packet(400);
                                        responsePacket.Add(datapackage.ToArray(), true);
                                        _ConnectionToLobeManager.SendPacket(responsePacket);

                                        if (File.Exists(String.Format("{0}/{1}", _Settings.CompletedWorkDirectory, job.GetGuid())))
                                        {
                                            File.Delete(String.Format("{0}/{1}", _Settings.CompletedWorkDirectory, job.GetGuid()));
                                        }

                                    }
                                }
                            }
                        }
                        lock (_PendingWork)
                        {
                            if (_PendingWork.Count < _Settings.WorkBufferCount && _Running && _CanRequestWork)
                            {
                                Packet p = new Packet(300); //Generate a work request packet
                                _ConnectionToLobeManager.SendPacket(p);
                                _CanRequestWork = false;
                            }
                        }
                        lock (_ConnectionToLobeManager)
                        {
                            if (_ConnectionToLobeManager.GetPacketsToProcessCount() > 0)
                            {
                                //manager is communicating
                                _TimeOfLastManagerComms = DateTime.Now;
                                lock (_PacketsToBeProcessed)
                                {
                                    _PacketsToBeProcessed.AddRange(_ConnectionToLobeManager.GetPacketsToProcess());
                                }
                            }
                            if (DateTime.Now - _TimeOfLastManagerComms > _TimeBeforeManagerConsideredLost)
                            {
                                //Disconnect as it seems the manager isnt there , this will cause an attempted reconnect above
                                _ConnectionToLobeManager.Disconnect();

                            }
                        }
                        lock (_PacketsToBeProcessed)
                        {
                            foreach (Packet p in _PacketsToBeProcessed) HandelIncomingPacket(p);
                            _PacketsToBeProcessed.Clear();
                        }
                    }
                }
                Thread.Sleep(100);
            }
            lock (_ActiveWorkerServices)
            {
                foreach (WorkerThread aWs in _ActiveWorkerServices)
                {
                    aWs.StopGracefully();
                }
            }
            AnnounceStatus("Lobe Worker Exiting");
            Dispose();
        }
Esempio n. 48
0
        private static Packet DemoPicture()
        {
            var uri = new Uri("blackfin.png", UriKind.Relative);
            var image = new BitmapImage(uri);

            var text = new TextFile('A') {{"<picture B/>", DisplayMode.Rotate}};
            var pic = new PictureFile('B', image, ColorFormat.Monochrome);

            var files = new FileTable {
                text, pic,
            };

            var packet = new Packet();
            packet.SetMemory(files);
            packet.Add(new WriteTextCommand(text));
            packet.Add(new WritePictureCommand(pic));
            return packet;
        }