C++ Revolution - Sockets (Part 1)

Page 2 of 2 FirstFirst 12
Results 16 to 26 of 26
  1. #16
    Alpha Member Moogly is offline
    MemberRank
    Feb 2008 Join Date
    Pool LidoLocation
    2,322Posts

    Re: C++ Revolution - Sockets (Part 1)

    Correct me if I'm wrong but this to me looks like a C++ .NET Project which means in reality this code is running in virtual memory completely managed by .NET which means this isn't a native C++ application, so you gain no benefits over C# by doing this.

    Edit:

    In any case this is useless without encoding coded.

  2. #17
    Web & Interaction Design Gangnam is offline
    MemberRank
    Dec 2010 Join Date
    Lincoln, UKLocation
    1,983Posts

    Re: C++ Revolution - Sockets (Part 1)

    Looks good,

    was you aware it says DESTIY ? ;)

  3. #18
    Alpha Member Caustik is offline
    MemberRank
    May 2011 Join Date
    LondonLocation
    1,837Posts

    Re: C++ Revolution - Sockets (Part 1)

    Why are you using managed C++ (C++ based on the .NET framework)?
    Just a question
    Posted via Mobile Device

  4. #19
    Valued Member BetterWay is offline
    MemberRank
    Dec 2011 Join Date
    The NetherlandsLocation
    146Posts

    Re: C++ Revolution - Sockets (Part 1)

    I'm busy with the Wire/Base64 Encoding/Decoding in C++ now, and about the managed C++ I can turn it into unmanaged?

    EDIT: Managed into Unmanaged will make List's impossible for now, I'll try this later, first finish the Wire/Bas64 encoding..

    Code:
    	public ref class WireEncoding
    	{
    	public:
    
    		 static array<Byte> ^EncodeInt64(Int64 i)
    		{
    			array<Byte> ^wf = gcnew array<Byte>(6);
    			Byte Negative = 72;
    			Byte Positive = 73;
    			int pos = 0;
    			int numBytes = 1;
    			int startPos = pos;
    			int NegativeMask = i >= 0 ? 0 : 4;
    
    			i = Math::Abs(i);
    			wf[pos++] = Convert::ToByte(64 + (i & 3));
    
    			for (i >>= 2; i != 0; i >>= 6)
    			{
    				numBytes++;
    				wf[pos++] = Convert::ToByte(64 + (i & 0x3f));
    			}
    			wf[startPos] = Convert::ToByte(wf[startPos] | numBytes << 3 | NegativeMask);
    
    			array<Byte> ^bzData = gcnew array<Byte>(numBytes);
    
    			for (int x = 0; x < numBytes; x++)
    			{
    				bzData[x] = wf[x];
    			}
    			return bzData;
    		}
    		 static array<Byte> ^EncodeInt32(int i)
    		{
    			array<Byte> ^wf = gcnew array<Byte>(6);
    			Byte Negative = 72;
    			Byte Positive = 73;
    
    			int pos = 0;
    			int numBytes = 0;
    			int NegativeMask = i >= 0 ? 0 : 4;
    			int startPos = pos;
    
    			i = Math::Abs(i);
    
    			wf[pos++] = Convert::ToByte(64 + (i & 3));
    
    			for (i >>= 2; i != 0; i >>= 6)
    			{
    				numBytes++;
    
    				wf[pos++] = Convert::ToByte(64 + (i & 0x3f));
    			}
    
    			wf[startPos] = Convert::ToByte(wf[startPos] | numBytes << 3 | NegativeMask);
    			
    			array<Byte> ^bzData = gcnew array<Byte>(numBytes);
    
    			for (int x = 0; x < numBytes; x++)
    			{
    				bzData[x] = wf[x];
    			}
    			return bzData;
    		}
    		static int DecodeInt32(array<Byte> ^bzData, int totalBytes)
    		{
    			int pos = 0;
    			int v = 0;
    
    			bool Negative = (bzData[pos] & 4) == 4;
    
    			totalBytes = bzData[pos] >> 3 & 7;
    
    			v = bzData[pos] & 3;
    
    			pos++;
    
    			int shiftAmount = 2;
    
    			for (int b = 1; b < totalBytes; b++)
    			{
    				v |= (bzData[pos] & 0x3f) << shiftAmount;
    				shiftAmount = 2 + 6 * b;
    				pos++;
    			}
    
    			if(Negative == true)
    			{
    				v *= -1;
    			}
    			return v;
    		}
    		 static array<Byte> ^EncodeInt32(Int32 i, int numBytes)
    		{
                array<Byte> ^bzRes = gcnew array<Byte>(numBytes);
    
                for (int j = 1; j <= numBytes; j++)
                {
                   int k = ((numBytes - j) * 6);
                    bzRes[j - 1] = (Byte)(0x40 + ((i >> k) & 0x3f));
                }
    
                return bzRes;
    		}
    	};
    Decode Base64:
    Code:
    		static int DecodeB64(String ^base)
    		{
    			array<wchar_t> ^val = base->ToCharArray();
               int intTot = 0;
               int y = 0;
                for (int x = (val->Length - 1); x >= 0; x--)
                {
                   static int intTmp = (int)(Byte)((val[x] - 64));
                    if (y > 0)
                    {
    					intTmp = intTmp * (int)(Math::Pow(64, y));
                    }
                    intTot += intTmp;
                    y++;
                }
                return intTot;
    		}
    Start @ ServerMessage:
    Code:
    		static void AddByte(unsigned char Bits)
    		{
    			mBody->Add(Bits);
    		}
    		static void AddBytes(array<unsigned char> ^B)
    		{
    			mBody->AddRange(B);
    		}
    		static void AppendInt32(int base)
    		{
    			AddBytes(WireEncoding::EncodeInt32(base));
    		}
    		static void AppendStringWithBreak(String^ s, unsigned char b)
    		{
    			AddBytes(Encoding::ASCII->GetBytes(s));
    			AddByte(b);
    		}
    Last edited by BetterWay; 22-12-11 at 01:11 PM.

  5. #20
    C# | C++ Emerica is offline
    MemberRank
    Oct 2010 Join Date
    GermanyLocation
    437Posts

    Re: C++ Revolution - Sockets (Part 1)

    Quote Originally Posted by Moogly View Post
    Correct me if I'm wrong but this to me looks like a C++ .NET Project which means in reality this code is running in virtual memory completely managed by .NET which means this isn't a native C++ application, so you gain no benefits over C# by doing this.

    Edit:

    In any case this is useless without encoding coded.
    you're right. This is .NET...

    I prefer native C++

  6. #21
    Valued Member BetterWay is offline
    MemberRank
    Dec 2011 Join Date
    The NetherlandsLocation
    146Posts

    Re: C++ Revolution - Sockets (Part 1)

    I programmed C++ all the time in .NET Framework, I won't make it Native (Not now for sure.) because I can't convert a couple of things into Native only..

    When I found anything to do this (Which will take a while..) I'll do this..

    For now I'll take a look in some C++ Books from my job, to find some things out (Things you can't use from .NET into Native only)..

    For now, I'll go forward with this, In future I should make it Native only.

  7. #22
    Web & Interaction Design Gangnam is offline
    MemberRank
    Dec 2010 Join Date
    Lincoln, UKLocation
    1,983Posts

    Re: C++ Revolution - Sockets (Part 1)

    Quote Originally Posted by BetterWay View Post
    I programmed C++ all the time in .NET Framework, I won't make it Native (Not now for sure.) because I can't convert a couple of things into Native only..

    When I found anything to do this (Which will take a while..) I'll do this..

    For now I'll take a look in some C++ Books from my job, to find some things out (Things you can't use from .NET into Native only)..

    For now, I'll go forward with this, In future I should make it Native only.
    Awesome, seems better in native?

  8. #23
    Valued Member BetterWay is offline
    MemberRank
    Dec 2011 Join Date
    The NetherlandsLocation
    146Posts

    Re: C++ Revolution - Sockets (Part 1)

    I toke a look at some books, not even reading it, but it looks awesome lol'd
    I found NCurses for Native Consoles so I'll try some things out..

    At this moment, I'm busy with PacketHandling (.NET Framework..)

    Code:
    		static void OnReceive(IAsyncResult^ asyncResult)
    		{
    			StateObject ^so = safe_cast<StateObject^>(asyncResult->AsyncState);
    			Socket ^s = so->workSocket;
    
    			int read = s->EndReceive(asyncResult);
    			if(read > 0)
    			{
    				so->sb->Append( Encoding::ASCII->GetString( so->buffer, 0, read ) );
    				String ^StringsInPacket = so->sb->ToString();
    				s->BeginReceive( so->buffer, 0, so->BUFFER_SIZE, SocketFlags::None,
    				gcnew AsyncCallback( &OnReceive ), so );
    				if(StringsInPacket->ToString()->Contains("<policy-file-request/>"))
    				{
    					array<Byte> ^GotBytesFromPacket = Encoding::ASCII->GetBytes("<?xml version=\"1.0\"?> " +
    					              "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\"> " +
    					              "<cross-domain-policy> " +
    					              "<allow-access-from domain=\"*\" to-ports=\"*\" /> " +
    					              "</cross-domain-policy>\x0");
    					s->Send(GotBytesFromPacket, GotBytesFromPacket->Length, SocketFlags::None);
    					Console::WriteLine("Send policy to client, Wait for response.");
    
    					s->BeginReceive( so->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None,
    					gcnew AsyncCallback( &OnReceive ), so );
    				}
    				else
    				{
    					if(StringsInPacket->Length > 0)
    					{
    						int packetint = PacketRequests::DecodeB64(StringsInPacket->Substring(1,2));
    						PacketRequests::HandlePacket(StringsInPacket->Substring(3, packetint), s);
    						StringsInPacket->Remove(0, 3 + packetint);
    					}
    				}
    			}
    		}
    Code:
    		static void HandlePacket(String ^IDs, Socket ^s)
    		{
    			int dec = DecodeB64(IDs->Substring(0, 2));
    			if(Packets[dec] == nullptr)
    			{
    				Console::WriteLine("Not Invoked: " + IDs + " Decimal " + dec);
    			}
    			else
    			{
    				Packets[dec]->Invoke(s);
    				Console::WriteLine("Invoked: " + IDs + " Decimal " + dec);
    			}
    		}
    Code:
    		static void SendPacket(String ^Data, Socket ^s)
    		{
    			try
    			{
    				array<Byte> ^BytesData = Encoding::ASCII->GetBytes(Data);
    				Console::WriteLine("[SND] . " + Encoding::ASCII->GetString(BytesData)->ToString());
    				s->BeginSend(BytesData, 0, BytesData->Length, SocketFlags::None, gcnew AsyncCallback(&OnSend), s);
    			}
    			catch (Exception^ e)
    			{
    				Console::WriteLine(e);
    			}
    		}
    Code:
    	delegate void PacketHandler(Socket ^s);
    	static Dictionary<int, PacketHandler^> ^Packets = gcnew Dictionary<int, PacketHandler^>();
    		static void LoadRequests()
    		{
    			RegisterOthers();
    		}
    		static void Register(int ID, PacketHandler^ PacketH)
    		{
    			if(Packets->ContainsKey(ID))
    			{
    				//nothing
    			}
    			Packets->Add(ID, PacketH);
    		}
    		static void RegisterOthers()
    		{
    			Register(206, gcnew PacketHandler(&HandleSessionDetails));
    			Register(415, gcnew PacketHandler(&HandleTicket));
    		}

  9. #24
    Member Aerospark is offline
    MemberRank
    May 2011 Join Date
    Canadia LandLocation
    90Posts

    Re: C++ Revolution - Sockets (Part 1)

    Nice development, but it's .NET. D:

    Though .NET is fine, it does somewhat defeat the propose of moving to C++, as its just as limiting as C#.

    If you want a more native approach but don't want to have to put a massive amount of work into platform specific implementations I'd recommend taking a look at Qt in the future. Though it may not be applicable to this project, I think it may be usefull to you.

    I actually started an open source server core in C++ using Qt a few months back. The SVN temporarily is down, but it may be helpful.

    Oh also, C++ has this cool feature where you can define operators inline. It's usefull for a lot of things, for example packet processing:
    PHP Code:
    #ifndef FLASHPACKET_H
    #define FLASHPACKET_H
    #include <QString>
    #include "utils.h"

    class FlashClient;

    class 
    HabboPacket
    {
    public:
        
    inline HabboPacket(){}
        
    inline HabboPacket(QByteArray data){buffer data;}
        
    inline HabboPacket(int headerid){buffer QByteArray(Utils::encodeB64(headerid2).toStdString().c_str());} // there HAS to be a better way to convert a QString to a QByteArray...

        // WRITE METHODS
        
    inline void operator+=(QString r) { appendString(r); }
        
    inline void operator+=(double i) { appendDouble(i); }
        
    inline void operator+=(qint32 r) { appendInt(r); }
        
    inline void operator+=(quint32 r) { appendUInt(r); }
        
    inline void operator+=(char c) { appendChar(c); }
        
    inline void operator+=(bool b) { appendBool(b); }

        
    inline HabboPacket &operator+(QString r) { operator +=(r); return *this; } // im sure passing to other inline operators doesnt add overhead...
        
    inline HabboPacket &operator+(double i) { operator +=(i); return *this; }
        
    inline HabboPacket &operator+(qint32 r) { operator +=(r); return *this; }
        
    inline HabboPacket &operator+(quint32 r) { operator +=(r); return *this; }
        
    inline HabboPacket &operator+(bool b) { operator +=(b); return *this; }
        
    inline HabboPacket &operator+(char c) { operator +=(c); return *this; }

        
    inline HabboPacket &operator<<(QString r) { operator +=(r); return *this; }
        
    inline HabboPacket &operator<<(double i) { operator +=(i); return *this; }
        
    inline HabboPacket &operator<<(qint32 r) { operator +=(r); return *this; }
        
    inline HabboPacket &operator<<(quint32 r) { operator +=(r); return *this; }
        
    inline HabboPacket &operator<<(bool b) { operator +=(b); return *this; }
        
    inline HabboPacket &operator<<(char c) { operator +=(c); return *this; }

        
    inline void appendString(QString rchar delimiter='\002'){ buffer += rbuffer += delimiter;}
        
    inline void appendDouble(double ichar delimiter='\002'){ buffer += QString::number(i'g'2); buffer += delimiter; }
        
    inline void appendChar(char c){ buffer += c; }
        
    inline void appendInt(qint32 r){ buffer += Utils::encodeVL64(r); }
        
    inline void appendUInt(quint32 r){ buffer += Utils::encodeVL64(r); }
        
    inline void appendBool(bool b){ buffer += b?"I":"H"; }
        
    inline void appendRawInt(qint32 i){ buffer += QString::number(i); }
        
    inline void appendRawUInt(quint32 i){ buffer += QString::number(i); }
        
    inline void appendRawString(QString r){ buffer += r; }

        
    // READ METHODS
        
    inline bool    eof(){return position >= buffer.length();}
        
    inline int     available(){return buffer.length() - position;}
        
    inline int     readB64(){return Utils::decodeB64(buffer.mid(position+=2,2));} // TODO: Implement this plz
        
    inline int     readInt(){return readB64();}
        
    inline QString readString(){int len=readB64(); return buffer.mid(position+=lenlen);}
        
    inline char    read(){return buffer.at(position++);}

    private:
        
    friend class FlashClient;
        
    int header;
        
    int position;
        
    QByteArray buffer;
    };

    #endif // FLASHPACKET_H 
    Good luck :)
    Last edited by Aerospark; 25-12-11 at 07:35 PM.

  10. #25
    Alpha Member Zak© is offline
    MemberRank
    Oct 2007 Join Date
    2,693Posts

    Re: C++ Revolution - Sockets (Part 1)

    Quote Originally Posted by BetterWay View Post
    I toke a look at some books, not even reading it, but it looks awesome lol'd
    I found NCurses for Native Consoles so I'll try some things out..

    At this moment, I'm busy with PacketHandling (.NET Framework..)

    Code:
            static void OnReceive(IAsyncResult^ asyncResult)
            {
                StateObject ^so = safe_cast<StateObject^>(asyncResult->AsyncState);
                Socket ^s = so->workSocket;
    
                int read = s->EndReceive(asyncResult);
                if(read > 0)
                {
                    so->sb->Append( Encoding::ASCII->GetString( so->buffer, 0, read ) );
                    String ^StringsInPacket = so->sb->ToString();
                    s->BeginReceive( so->buffer, 0, so->BUFFER_SIZE, SocketFlags::None,
                    gcnew AsyncCallback( &OnReceive ), so );
                    if(StringsInPacket->ToString()->Contains("<policy-file-request/>"))
                    {
                        array<Byte> ^GotBytesFromPacket = Encoding::ASCII->GetBytes("<?xml version=\"1.0\"?> " +
                                      "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\"> " +
                                      "<cross-domain-policy> " +
                                      "<allow-access-from domain=\"*\" to-ports=\"*\" /> " +
                                      "</cross-domain-policy>\x0");
                        s->Send(GotBytesFromPacket, GotBytesFromPacket->Length, SocketFlags::None);
                        Console::WriteLine("Send policy to client, Wait for response.");
    
                        s->BeginReceive( so->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None,
                        gcnew AsyncCallback( &OnReceive ), so );
                    }
                    else
                    {
                        if(StringsInPacket->Length > 0)
                        {
                            int packetint = PacketRequests::DecodeB64(StringsInPacket->Substring(1,2));
                            PacketRequests::HandlePacket(StringsInPacket->Substring(3, packetint), s);
                            StringsInPacket->Remove(0, 3 + packetint);
                        }
                    }
                }
            }
    Code:
            static void HandlePacket(String ^IDs, Socket ^s)
            {
                int dec = DecodeB64(IDs->Substring(0, 2));
                if(Packets[dec] == nullptr)
                {
                    Console::WriteLine("Not Invoked: " + IDs + " Decimal " + dec);
                }
                else
                {
                    Packets[dec]->Invoke(s);
                    Console::WriteLine("Invoked: " + IDs + " Decimal " + dec);
                }
            }
    Code:
            static void SendPacket(String ^Data, Socket ^s)
            {
                try
                {
                    array<Byte> ^BytesData = Encoding::ASCII->GetBytes(Data);
                    Console::WriteLine("[SND] . " + Encoding::ASCII->GetString(BytesData)->ToString());
                    s->BeginSend(BytesData, 0, BytesData->Length, SocketFlags::None, gcnew AsyncCallback(&OnSend), s);
                }
                catch (Exception^ e)
                {
                    Console::WriteLine(e);
                }
            }
    Code:
        delegate void PacketHandler(Socket ^s);
        static Dictionary<int, PacketHandler^> ^Packets = gcnew Dictionary<int, PacketHandler^>();
            static void LoadRequests()
            {
                RegisterOthers();
            }
            static void Register(int ID, PacketHandler^ PacketH)
            {
                if(Packets->ContainsKey(ID))
                {
                    //nothing
                }
                Packets->Add(ID, PacketH);
            }
            static void RegisterOthers()
            {
                Register(206, gcnew PacketHandler(&HandleSessionDetails));
                Register(415, gcnew PacketHandler(&HandleTicket));
            }
    This just looks like what George2000 did ported in C++?

  11. #26
    Valued Member BetterWay is offline
    MemberRank
    Dec 2011 Join Date
    The NetherlandsLocation
    146Posts

    Re: C++ Revolution - Sockets (Part 1)

    The idea of packethandling by receiving yes.



Page 2 of 2 FirstFirst 12

Advertisement