C++ Revolution - Sockets (Part 1)

Page 1 of 2 12 LastLast
Results 1 to 25 of 26
  1. #1
    Valued Member BetterWay is offline
    MemberRank
    Dec 2011 Join Date
    The NetherlandsLocation
    146Posts

    C++ Revolution - Sockets (Part 1)

    Why C++?
    Because it is a nice Coding language for Sockets/Sessions.

    Huh? Revolution?
    Yes, Most of all emulators are in C# or Java, so I wanted to try this in C++ :)

    How did you do this?
    Simple, a basic Socket system which accepts the connections from the client (No big deal at all..)
    But efficient for now, and soon there will be more :)

    Code
    SocketInit.h
    Code:
    namespace Sockets {
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::IO;
    using namespace System::Threading;
    using namespace System::Net;
    using namespace System::Security::Cryptography;
    using namespace System::Net::Sockets;
    using namespace System::Text;
    using namespace System::Globalization;
    using namespace System::Diagnostics;
    	ref class SocketInitializer
    	{
    	public:
    		static void DoSockets()
    		{
    			IPHostEntry^ Entry = Dns::GetHostByAddress("IPHERE");
    			IPEndPoint^ endPoint = gcnew IPEndPoint(Entry->AddressList[0], PORTHERE);
    			Socket ^SocketInit = gcnew Socket(endPoint->Address->AddressFamily, SocketType::Stream, ProtocolType::Tcp);
    			try
    			{
    				SocketInit->Bind(endPoint);
    				SocketInit->Listen(5);
    				Console::WriteLine("Intialized Sockets successfull");
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    				while(true)
    				{
    					Thread::Sleep(100);
    				}
    			}
    			try
    			{
    				SocketInit->BeginAccept(gcnew AsyncCallback(&OnAccept), SocketInit);
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    			}
    		}
    		static void OnAccept(IAsyncResult^ asyncResult)
    		{
    			Console::WriteLine("Incoming connection!");
    		}
    	};
    };
    Then in your Main() from your console application just add:
    Code:
    Sockets::SocketInitializer::DoSockets();
    Replace IPHERE and PORTHERE to your LOCAL Ip and REMOTE Port.

    Screen

    Questions? ask them down :)
    Last edited by BetterWay; 21-12-11 at 08:58 AM. Reason: Changes


  2. #2
    Proficient Member Squard is offline
    MemberRank
    Dec 2011 Join Date
    155Posts

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

    Why using Thread.Sleep(); You wanna make anything Lagg?

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

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

    This Thread::Sleep(); only act when there is an Exception by listening or binding..

  4. #4
    [R8]ℓσℓ32 caja is offline
    MemberRank
    Oct 2008 Join Date
    Here!Location
    1,502Posts

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

    This is C# LOL

  5. #5
    Gamma Spamma Liam is offline
    MemberRank
    Dec 2011 Join Date
    Down UnderLocation
    2,945Posts

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

    Quote Originally Posted by caja View Post
    This is C# LOL
    You must have problems, this is for C++, not C#.

    Cool release, I do enjoy seeing people coding in C++ in the Habbo section.

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

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

    The whole point of C++ is that it's cross platform...
    Write your sockets for unix as well.
    Posted via Mobile Device

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

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

    Quote Originally Posted by caja View Post
    This is C# LOL
    I think u really got no idea of coding languages, but anyways, it is C++. like said by others.

    Quote Originally Posted by MyKi View Post
    You must have problems, this is for C++, not C#.

    Cool release, I do enjoy seeing people coding in C++ in the Habbo section.
    Thanks :)

    Quote Originally Posted by Caustik View Post
    The whole point of C++ is that it's cross platform...
    Write your sockets for unix as well.
    Posted via Mobile Device
    I'll take a look, but I don't promise anything ^^

  8. #8
    Gamma Spamma Liam is offline
    MemberRank
    Dec 2011 Join Date
    Down UnderLocation
    2,945Posts

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

    Well, I hope you go well :] - I'm going to PM you if you're interested in something.

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

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

    I was just wondering about packet reading in C++ and I think I got it well done :)
    StateObject() ref class from msdn @ Microsoft.

    Code:
    namespace SocketManager {
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::IO;
    using namespace System::Threading;
    using namespace System::Net;
    using namespace System::Security::Cryptography;
    using namespace System::Net::Sockets;
    using namespace System::Text;
    using namespace System::Globalization;
    using namespace System::Diagnostics;
    	public ref class StateObject
    	{
    	public:
    	    literal int BUFFER_SIZE = 1024;
    		Socket^ workSocket;
    	    array<Byte>^ buffer;
    	    StringBuilder^ sb;
    	    StateObject() : workSocket( nullptr )
    	    {
    	       buffer = gcnew array<Byte>(BUFFER_SIZE);
    	      sb = gcnew StringBuilder;
    	    }
    	};
    	ref class SocketInitializer
    	{
    	public:
    		static void DoSockets()
    		{
    			array<Byte> ^PacketArray = gcnew array<Byte>(5000);
    			IPHostEntry^ Entry = Dns::GetHostByAddress("172.16.0.6");
    			IPEndPoint^ endPoint = gcnew IPEndPoint(Entry->AddressList[0], 30002);
    			Socket ^SocketInit = gcnew Socket(endPoint->Address->AddressFamily, SocketType::Stream, ProtocolType::Tcp);
    			try
    			{
    				SocketInit->Bind(endPoint);
    				SocketInit->Listen(1000);
    				Console::WriteLine("Intialized Sockets successfull");
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    				while(true)
    				{
    					Thread::Sleep(100);
    				}
    			}
    			try
    			{
    				SocketInit->BeginAccept(gcnew AsyncCallback(&OnAccept), SocketInit);
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    				while(true)
    				{
    					Thread::Sleep(100);
    				}
    			}
    		}
    		static void OnAccept(IAsyncResult^ asyncResult)
    		{
    			Socket^ SocketH = safe_cast<Socket^>(asyncResult->AsyncState);
    			Socket^ hSocket = SocketH->EndAccept(asyncResult);
    			StateObject^ hSocketS = gcnew StateObject();
    			hSocketS->workSocket = hSocket;
    			hSocket->BeginReceive(hSocketS->buffer, 0, hSocketS->BUFFER_SIZE, SocketFlags::None, gcnew AsyncCallback(&OnReceive), hSocketS);
    			Console::WriteLine("Incoming connection!");
    		}
    		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, StateObject::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 );
    				}
    			}
    		}
    	};
    };
    Add to your console application Main thread:
    Code:
    SocketManager::SocketInitializer::DoSockets();
    This evening or tomorrow I'll start on the Packethandlers and Registering of them :)

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

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

    The problem is that you have <sys/types> and <sys/sockets> at your disposal, which will make it cross-platform, rather than rely on the winsock windows-only sockets. Unix also opens up a greater number of sockets than Windows. Just a suggestion though.

  11. #11
    Ultra Light Beam Makarov is offline
    MemberRank
    Apr 2010 Join Date
    GothamLocation
    3,622Posts
    I'm glad someone is finally bringing substance and originality to this section.

    Sent from my DROID2 GLOBAL using Tapatalk

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

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

    I coded only things like Memory Edit/Bypasses (Assembly) for FPS Games in C++ before, so all this stuff is very new for me right now, and I thought when ppl code Emulators in C# Why it can't be in C++? thats my point of this whole thing, or I'll fix it for Unix, got no idea.

    Added Thread::Sleep(21) and while(true) for optimal receiving (Thread:Sleep(21) wont make it laggy at all, the problem is, if you don't add sleeps in C++ the program overloads, and will crash after a while..)

    Code:
    namespace SocketManager {
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::IO;
    using namespace System::Threading;
    using namespace System::Net;
    using namespace System::Security::Cryptography;
    using namespace System::Net::Sockets;
    using namespace System::Text;
    using namespace System::Globalization;
    using namespace System::Diagnostics;
    	public ref class StateObject
    	{
    	public:
    	    literal int BUFFER_SIZE = 1024;
    		Socket^ workSocket;
    	    array<Byte>^ buffer;
    	    StringBuilder^ sb;
    	    StateObject() : workSocket( nullptr )
    	    {
    	       buffer = gcnew array<Byte>(BUFFER_SIZE);
    	      sb = gcnew StringBuilder;
    	    }
    	};
    	ref class SocketInitializer
    	{
    	public:
    		static void DoSockets()
    		{
    			array<Byte> ^PacketArray = gcnew array<Byte>(5000);
    			IPHostEntry^ Entry = Dns::GetHostByAddress("172.16.0.6");
    			IPEndPoint^ endPoint = gcnew IPEndPoint(Entry->AddressList[0], 30002);
    			Socket ^SocketInit = gcnew Socket(endPoint->Address->AddressFamily, SocketType::Stream, ProtocolType::Tcp);
    			try
    			{
    				SocketInit->Bind(endPoint);
    				SocketInit->Listen(1000);
    				Console::WriteLine("Intialized Sockets successfull");
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    				while(true)
    				{
    					Thread::Sleep(100);
    				}
    			}
    			try
    			{
    				while(true)
    				{
    					SocketInit->BeginAccept(gcnew AsyncCallback(&OnAccept), SocketInit);
    					Thread::Sleep(21);
    				}
    			}
    			catch(Exception ^e)
    			{
    				Console::WriteLine("Exception: " + e->StackTrace);
    				while(true)
    				{
    					Thread::Sleep(100);
    				}
    			}
    		}
    		static void OnAccept(IAsyncResult^ asyncResult)
    		{
    			Socket^ SocketH = safe_cast<Socket^>(asyncResult->AsyncState);
    			Socket^ hSocket = SocketH->EndAccept(asyncResult);
    			StateObject^ hSocketS = gcnew StateObject();
    			hSocketS->workSocket = hSocket;
    			hSocket->BeginReceive(hSocketS->buffer, 0, hSocketS->BUFFER_SIZE, SocketFlags::None, gcnew AsyncCallback(&OnReceive), hSocketS);
    			Console::WriteLine("Incoming connection!");
    		}
    		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, StateObject::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
    				{
    					Console::WriteLine("[RCV] " + StringsInPacket->ToString());
    				}
    			}
    		}
    	};
    };
    Screen:
    Last edited by BetterWay; 21-12-11 at 02:08 PM.

  13. #13
    Proficient Member Squard is offline
    MemberRank
    Dec 2011 Join Date
    155Posts

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

    How did you make your Console Orange?

    Quote Originally Posted by Squard View Post
    How did you make your Console Orange?
    OMG my fail. Its windows srry.

  14. #14
    Live Ocottish Sverlord Joopie is online now
    LegendRank
    Jun 2010 Join Date
    The NetherlandsLocation
    2,773Posts

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

    Quote Originally Posted by Squard View Post
    Why using Thread.Sleep(); You wanna make anything Lagg?
    He's using it in a while true, If he didn't do that, you get a high cpu as result

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

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

    If you want to make the source cross-platform...
    Tutorial: Using the C++ Sockets library
    I've been reading into this, seems interesting.

  16. #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.

  17. #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 ? ;)

  18. #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

  19. #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.

  20. #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++

  21. #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.

  22. #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?

  23. #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));
    		}

  24. #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.

  25. #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++?



Page 1 of 2 12 LastLast

Advertisement