collapse collapse

* Who's Online

  • Dot Guests: 77
  • Dot Hidden: 0
  • Dot Users: 0

There aren't any users online.

* Board Stats

  • stats Total Members: 88
  • stats Total Posts: 11163
  • stats Total Topics: 1699
  • stats Total Categories: 4
  • stats Total Boards: 76
  • stats Most Online: 248

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - powerfear

Pages: [1]
1
C++ / C++ code cave
« on: May 15, 2010, 01:08:41 pm »
ok here's how you easily make codecave with C++ also called detours

note: this is a basic way to hook, and might be detected by online game that use anti-hacking system

Ok so start by creating a new project Win32 project

Application type: DLL

Additional options: Empty project

Ok so basicaly how it work is that you create a __declspec(naked) void function, those kind of function don't have any C++ prefix or anything so you can use pure asm with them.

inside the function you insert the desired asm content of your codecave inside
__asm
{

}
 you can also mix up with some C++ if you know what you're doing.

now you need to call your codecave at your desired location so we need a hooking function (creating a jmp to the code cave)

here's a simple one with the little advantage of automaticly using VirtualProtect to allow writting on the specified memory area if it's protected

Code: C
  1. void CopyBuffer(BYTE *Buffer, int Size, DWORD *Address)
  2. {
  3.         DWORD pPrevious = 0;
  4.         VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, &pPrevious);
  5.         memcpy(Address, Buffer, Size);
  6.         VirtualProtect(Address, Size, pPrevious, &pPrevious);
  7. }
  8.  
  9. void SetupHook(DWORD Function, DWORD Hook, int Size)
  10. {
  11.         Hook = Hook - Function - 5;
  12.         BYTE bHook[4];
  13.         memcpy(bHook,(void*)&Hook,4);
  14.         BYTE Buffer[10];
  15.         memset(Buffer,0x90,10);
  16.         Buffer[0] = 0xE9;
  17.         Buffer[1] = bHook[0];
  18.         Buffer[2] = bHook[1];
  19.         Buffer[3] = bHook[2];
  20.         Buffer[4] = bHook[3];
  21.         CopyBuffer(Buffer, Size, (DWORD*)Function);
  22. }
  23.  

now let's look at a fake example i made up for a game that don't exist

Code: C
  1. #include <windows.h>
  2. DWORD hookaddy = 0x004B9302;
  3. DWORD addy = 0x004FC260;
  4. DWORD addy2 = hookaddy+5
  5. int loop = 50;
  6. __declspec(naked) void CodeCave()
  7. {
  8.         __asm
  9.         {
  10.                 MOV EAX,loop;
  11.                 loopstart:
  12.                 PUSH EAX;
  13.                 CALL addy1;
  14.                 POP EAX;
  15.                 DEC EAX;
  16.                 CMP EAX,0;
  17.                 JNZ loopstart;
  18.                 JMP addy2;
  19.         }
  20. }
  21.  
  22. void CopyBuffer(BYTE *Buffer, int Size, DWORD *Address)
  23. {
  24.         DWORD pPrevious = 0;
  25.         VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, &pPrevious);
  26.         memcpy(Address, Buffer, Size);
  27.         VirtualProtect(Address, Size, pPrevious, &pPrevious);
  28. }
  29.  
  30. void SetupHook(DWORD Function, DWORD Hook, int Size)
  31. {
  32.         Hook = Hook - Function - 5;
  33.         BYTE bHook[4];
  34.         memcpy(bHook,(void*)&Hook,4);
  35.         BYTE Buffer[10];
  36.         memset(Buffer,0x90,10);
  37.         Buffer[0] = 0xE9;
  38.         Buffer[1] = bHook[0];
  39.         Buffer[2] = bHook[1];
  40.         Buffer[3] = bHook[2];
  41.         Buffer[4] = bHook[3];
  42.         CopyBuffer(Buffer, Size, (DWORD*)Function);
  43. }
  44.  
  45. DWORD WINAPI dwMainThread(LPVOID)
  46. {
  47.         SetupHook(hookaddy,(DWORD)CodeCave,5);
  48.         return 0;
  49. }
  50.  
  51. BOOL WINAPI DllMain ( HMODULE hDll, DWORD dwReason, LPVOID lpReserved )
  52. {
  53.         DisableThreadLibraryCalls(hDll);
  54.         if ( dwReason == DLL_PROCESS_ATTACH )
  55.         {
  56.                 CreateThread(NULL, NULL, dwMainThread, NULL, NULL, NULL);
  57.         }
  58.         return TRUE;
  59. }
  60.  

The creating of a thread to do the SetupHook is optional there since i don't have anything else to do, but if you have other code you could put it inside the dwMainThread.

Ok so now i'll explain what the example do, since it's a .dll once it will be injected it will run the CreateThread function that will run the dwMainThread function in a separate thread then the game main thread, then it will call the SetupHook function that will change the opcode at the hookaddy to a jmp that will point to our codecave function address, now the hack itself let's see what it do, basicaly let's say the game had a function to add points, we replace the original call to the function with a jmp to our codecave inside our codecave we have a loop using eax that will call the function the number of time corresponding to our loop variable, as an option i could put a hotkey system in the dwMainThread to increase / decrease that variable. A far jump in ASM is 5 byte so after all the loop are done i make the codecave JMP back 5 byte after the call to our codecave so it continue to execute the normal code of the game.



[edited name=powerfear date=1273947022][/edited]

2
DirectX / D3D9 Tutorial 3: Loading an image from file and drawing it
« on: March 06, 2010, 10:28:01 am »
Loading an image from a file and drawing it

Code: C++
  1. #include <windows.h> //include windows header for some function like MessageBox, creating the window.
  2. #include "d3dx9.h" //include a directx header
  3. #include <stdio.h> //for the sprinf_s function used by DrawString
  4.  
  5. #pragma comment(lib, "d3dx9.lib") //link the library
  6. #pragma comment(lib, "d3d9.lib") //link the library
  7. #define Emsg(msg){MessageBox(NULL,msg,"Error",MB_OK|MB_ICONEXCLAMATION);} //macro for error pop-up
  8.  
  9. int WINDOW_WIDTH = 1024; //window width
  10. int WINDOW_HEIGHT = 768; //window height
  11. bool windowed = true; //window mode, change to false for full screen
  12.  
  13. IDirect3D9 *pD3D; //global variable that will be used by a couple of our function
  14. IDirect3DDevice9 *pDevice; //a device that will be used for msot of our function created inside *pD3D
  15. LPD3DXFONT pFont; //font variable to use with our create font function and to display text after
  16.  
  17. LPDIRECT3DTEXTURE9 imagetex; //textute our image will be loaded into
  18. LPD3DXSPRITE sprite; //sprite to display our image
  19. D3DXVECTOR3 imagepos; //vector for the position of the sprite
  20.  
  21. LRESULT CALLBACK wndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) //callback function for our GetMessage function on the while statement inside the main function
  22. {
  23.         switch(uMsg) //switch the MSG variable passed
  24.         {
  25.         case WM_CLOSE: //case it's a Window Close MSG
  26.                 PostQuitMessage(0); //Apply a Quit Message
  27.                 break;
  28.         }
  29.         return DefWindowProc(hWnd,uMsg,wParam,lParam); //pass the variable
  30. }
  31.  
  32. HRESULT initialize()
  33. {
  34.         if(FAILED(D3DXCreateTextureFromFile(pDevice,"test.png",&imagetex)))//first parameter is our device,second is the path to our image, third is a texture variable to load the image into
  35.         {
  36.                 Emsg("Failed to laod the image"); //error pop-up for debug purpose
  37.                 return E_FAIL; //return it failed
  38.         }
  39.         if(FAILED(D3DXCreateSprite(pDevice,&sprite)))//first parameter is our device, second is a empty sprite variable
  40.         {
  41.                 Emsg("Failed to create the sprite"); //error pop-up for debug purpose
  42.                 return E_FAIL; //return it failed
  43.         }
  44.         imagepos.x=8.0f; //coord x of our sprite
  45.         imagepos.y=18.0f; //coord y of out sprite
  46.         imagepos.z=0.0f; //coord z of out sprite
  47.         return S_OK;
  48. }
  49.  
  50. HRESULT render() //function where all Drawing/Render stuff go
  51. {
  52.         if(SUCCEEDED(pDevice->BeginScene())) //Call the BeginScene function with our Device and see if it succeeded, all drawing/render code go behind BeginScene and EndScene
  53.         {
  54.                 sprite->Begin(D3DXSPRITE_ALPHABLEND); //begin our sprite with alphablend so it support alpha, like png use alpha
  55.                 sprite->Draw(imagetex,NULL,NULL,&imagepos,0xFFFFFFFF); //Draw the sprite, first parameter is the image texture, 4th parameter is the position, last parameter is the color change leave to 0xFFFFFFFF for no change
  56.                 sprite->End(); //end the sprite
  57.                 pDevice->EndScene(); //Call the EndScene function with our Device
  58.                 return S_OK; //return it succeeded
  59.         }
  60.         return E_FAIL; //return it failed
  61. }
  62.  
  63. void CleanUp() //function to delete/release things to prevent memory leak
  64. {
  65.         if(pD3D) //check if pD3D ism't released
  66.                 pD3D->Release(); //release it
  67.         if(pDevice) //check if pDevice ism't released
  68.                 pDevice->Release(); //release it
  69.         if(sprite) //check if sprite ism't released
  70.                 sprite->Release(); //release it
  71.         if(imagetex) //check if imagetex ism't released
  72.                 imagetex->Release(); //release it
  73. }
  74.  
  75. int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) //our main function the first function called of the program
  76. {
  77.         WNDCLASSEX wc; //window class won't go in detail not related to this tutorial really
  78.         wc.cbSize = sizeof(WNDCLASSEX);
  79.         wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  80.         wc.lpfnWndProc = (WNDPROC)wndProc;
  81.         wc.cbWndExtra = 0;
  82.         wc.cbClsExtra = 0;
  83.         wc.hInstance = hInstance;
  84.         wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  85.         wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  86.         wc.hbrBackground = NULL;
  87.         wc.lpszMenuName = NULL;
  88.         wc.lpszClassName = "D3DTEST"; //class name
  89.         wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
  90.  
  91.         RECT rect; //window rectangle
  92.         rect.top = (long)0;
  93.         rect.left = (long)0;
  94.         rect.right = WINDOW_WIDTH; //use our global WINDOW_WIDTH variable
  95.         rect.bottom = WINDOW_HEIGHT; //use our global WINDOW_HEIGHT variable
  96.  
  97.         if(!RegisterClassEx(&wc)) //register the window cs
  98.         {
  99.                 Emsg("Could not register window class"); //error pop-up for debug purpose
  100.                 return 1; //return error
  101.         }
  102.  
  103.         AdjustWindowRectEx(&rect,WS_OVERLAPPEDWINDOW,false,WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); //set the window width and height with the rect above
  104.         //the D3DTEST must match the class name of the window class and D3D TEST is the window name
  105.         HWND hWindow = CreateWindowEx(NULL,"D3DTEST","D3D TEST",WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,0,0,rect.right-rect.left,rect.bottom-rect.top,NULL,NULL,hInstance,NULL); //create the window
  106.  
  107.         if(!hWindow) //if the window failed to create
  108.         {
  109.                 DestroyWindow(hWindow); //destroy the window
  110.                 UnregisterClass("D3DTEST",hInstance); //unregister our window class
  111.                 Emsg("Failed to create the window"); //error pop-up for debug purpose
  112.                 return 1; //return error
  113.         }
  114.  
  115.         ShowWindow(hWindow,SW_SHOW); //show our window
  116.         UpdateWindow(hWindow); //update our window
  117.         SetForegroundWindow(hWindow); //set our window on top
  118.         SetFocus(hWindow); //set the focus on our window
  119.  
  120.         D3DPRESENT_PARAMETERS d3dpp; //the presentation parameters that will be used when we will create the device
  121.         ZeroMemory(&d3dpp,sizeof(d3dpp)); //to be sure d3dpp is empty
  122.         d3dpp.Windowed = windowed; //use our global windowed variable to tell if the program is windowed or not
  123.         d3dpp.hDeviceWindow = hWindow; //give the window handle of the window we created above
  124.         d3dpp.BackBufferCount = 1; //set it to only use 1 backbuffer
  125.         d3dpp.BackBufferWidth = WINDOW_WIDTH; //set the buffer to our window width
  126.         d3dpp.BackBufferHeight = WINDOW_HEIGHT; //set the buffer to out window height
  127.         d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; //the backbuffer format
  128.         d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; //SwapEffect
  129.  
  130.         pD3D = Direct3DCreate9(D3D_SDK_VERSION); //Create the presentation parameters
  131.  
  132.         if(FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWindow,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&pDevice))) //create the device and check if it failed
  133.         {
  134.                 Emsg("Failed to create device"); //error pop-up for debug purpose
  135.                 CleanUp(); //call your CleanUp() function to prevent memory leak
  136.                 return 1; //exit the program return 1 error
  137.         }
  138.  
  139.         if(FAILED(initialize())) //call the initialize() function and check if it failed
  140.         {
  141.                 Emsg("Failed to initialize"); //error pop-up for debug purpose
  142.                 CleanUp(); //call your CleanUp() function to prevent memory leak
  143.                 return 1; //exit the program return 1 error
  144.         }
  145.  
  146.         MSG msg; //declare a MSG local variable for the GetMessage of the while loop
  147.         while(GetMessage(&msg,NULL,0,0)) //GetMessage reffer to the wndProc() function
  148.         {
  149.                 pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1.0f,0.0f); //Clear the screen with black, basically since we only draw text here it's like your background change the D3DCOLOR_XRGB(0,0,0) to change the color the 3 number additioned must make 255 maximum
  150.                 if(FAILED(render())) //call the function render() and verify if it worked
  151.                 {
  152.                         Emsg("Render failed"); //error pop-up for debug purpose
  153.                 }
  154.  
  155.                 pDevice->Present(NULL,NULL,NULL,NULL); //display your buffer on screen
  156.                 TranslateMessage(&msg); //translate the msg of the GetMessage of your while loop
  157.                 DispatchMessage(&msg); //dispath the msg of the GetMessage of your while loop
  158.         }
  159.         CleanUp(); //call your CleanUp() function to prevent memory leak
  160.         return 0; //return 0 no problem
  161. }
  162.  

note: if you test your program directly from your compiler you need to provide the full path to the image

3
DirectX / D3D9 Tutorial 2: Drawing a rectangle
« on: March 06, 2010, 10:01:54 am »
Drawing a rectangle

Code: C++
  1. #include <windows.h> //include windows header for some function like MessageBox, creating the window.
  2. #include "d3dx9.h" //include a directx header
  3.  
  4. #pragma comment(lib, "d3dx9.lib") //link the library
  5. #pragma comment(lib, "d3d9.lib") //link the library
  6. #define Emsg(msg){MessageBox(NULL,msg,"Error",MB_OK|MB_ICONEXCLAMATION);} //macro for error pop-up
  7.  
  8. int WINDOW_WIDTH = 1024; //window width
  9. int WINDOW_HEIGHT = 768; //window height
  10. bool windowed = true; //window mode, change to false for full screen
  11.  
  12. IDirect3D9 *pD3D; //global variable that will be used by a couple of our function
  13. IDirect3DDevice9 *pDevice; //a device that will be used for msot of our function created inside *pD3D
  14.  
  15. D3DRECT crec = {200, 200, 400, 600}; //position and dimensions of our rectangle
  16. LRESULT CALLBACK wndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) //callback function for our GetMessage function on the while statement inside the main function
  17. {
  18.         switch(uMsg) //switch the MSG variable passed
  19.         {
  20.         case WM_CLOSE: //case it's a Window Close MSG
  21.                 PostQuitMessage(0); //Apply a Quit Message
  22.                 break;
  23.         }
  24.         return DefWindowProc(hWnd,uMsg,wParam,lParam); //pass the variable
  25. }
  26.  
  27. HRESULT render() //function where all Drawing/Render stuff go
  28. {
  29.         if(SUCCEEDED(pDevice->BeginScene())) //Call the BeginScene function with our Device and see if it succeeded, all drawing/render code go behind BeginScene and EndScene
  30.         {
  31.                 //Clear a part of the screen to make a red rectangle, crec give the coord and the dimensions, and D3DCOLOR_XRGB(255,0,0) give the color
  32.                 pDevice->Clear( 1, &crec, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255,0,0), 0, 0 );
  33.                 pDevice->EndScene(); //Call the EndScene function with our Device
  34.                 return S_OK; //return it succeeded
  35.         }
  36.         return E_FAIL; //return it failed
  37. }
  38.  
  39. void CleanUp() //function to delete/release things to prevent memory leak
  40. {
  41.         if(pD3D) //check if pD3D ism't released
  42.                 pD3D->Release(); //release it
  43.         if(pDevice) //check if pDevice ism't released
  44.                 pDevice->Release(); //release it
  45. }
  46.  
  47. int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) //our main function the first function called of the program
  48. {
  49.         WNDCLASSEX wc; //window class won't go in detail not related to this tutorial really
  50.         wc.cbSize = sizeof(WNDCLASSEX);
  51.         wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  52.         wc.lpfnWndProc = (WNDPROC)wndProc;
  53.         wc.cbWndExtra = 0;
  54.         wc.cbClsExtra = 0;
  55.         wc.hInstance = hInstance;
  56.         wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  57.         wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  58.         wc.hbrBackground = NULL;
  59.         wc.lpszMenuName = NULL;
  60.         wc.lpszClassName = "D3DTEST"; //class name
  61.         wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
  62.  
  63.         RECT rect; //window rectangle
  64.         rect.top = (long)0;
  65.         rect.left = (long)0;
  66.         rect.right = WINDOW_WIDTH; //use our global WINDOW_WIDTH variable
  67.         rect.bottom = WINDOW_HEIGHT; //use our global WINDOW_HEIGHT variable
  68.  
  69.         if(!RegisterClassEx(&wc)) //register the window cs
  70.         {
  71.                 Emsg("Could not register window class"); //error pop-up for debug purpose
  72.                 return 1; //return error
  73.         }
  74.  
  75.         AdjustWindowRectEx(&rect,WS_OVERLAPPEDWINDOW,false,WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); //set the window width and height with the rect above
  76.         //the D3DTEST must match the class name of the window class and D3D TEST is the window name
  77.         HWND hWindow = CreateWindowEx(NULL,"D3DTEST","D3D TEST",WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,0,0,rect.right-rect.left,rect.bottom-rect.top,NULL,NULL,hInstance,NULL); //create the window
  78.  
  79.         if(!hWindow) //if the window failed to create
  80.         {
  81.                 DestroyWindow(hWindow); //destroy the window
  82.                 UnregisterClass("D3DTEST",hInstance); //unregister our window class
  83.                 Emsg("Failed to create the window"); //error pop-up for debug purpose
  84.                 return 1; //return error
  85.         }
  86.  
  87.         ShowWindow(hWindow,SW_SHOW); //show our window
  88.         UpdateWindow(hWindow); //update our window
  89.         SetForegroundWindow(hWindow); //set our window on top
  90.         SetFocus(hWindow); //set the focus on our window
  91.  
  92.         D3DPRESENT_PARAMETERS d3dpp; //the presentation parameters that will be used when we will create the device
  93.         ZeroMemory(&d3dpp,sizeof(d3dpp)); //to be sure d3dpp is empty
  94.         d3dpp.Windowed = windowed; //use our global windowed variable to tell if the program is windowed or not
  95.         d3dpp.hDeviceWindow = hWindow; //give the window handle of the window we created above
  96.         d3dpp.BackBufferCount = 1; //set it to only use 1 backbuffer
  97.         d3dpp.BackBufferWidth = WINDOW_WIDTH; //set the buffer to our window width
  98.         d3dpp.BackBufferHeight = WINDOW_HEIGHT; //set the buffer to out window height
  99.         d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; //the backbuffer format
  100.         d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; //SwapEffect
  101.  
  102.         pD3D = Direct3DCreate9(D3D_SDK_VERSION); //Create the presentation parameters
  103.  
  104.         if(FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWindow,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&pDevice))) //create the device and check if it failed
  105.         {
  106.                 Emsg("Failed to create device"); //error pop-up for debug purpose
  107.                 CleanUp(); //call your CleanUp() function to prevent memory leak
  108.                 return 1; //exit the program return 1 error
  109.         }
  110.  
  111.         MSG msg; //declare a MSG local variable for the GetMessage of the while loop
  112.         while(GetMessage(&msg,NULL,0,0)) //GetMessage reffer to the wndProc() function
  113.         {
  114.                 pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1.0f,0.0f); //Clear the screen with black, basically since we only draw text here it's like your background change the D3DCOLOR_XRGB(0,0,0) to change the color the 3 number additioned must make 255 maximum
  115.                 if(FAILED(render())) //call the function render() and verify if it worked
  116.                 {
  117.                         Emsg("Render failed"); //error pop-up for debug purpose
  118.                 }
  119.  
  120.                 pDevice->Present(NULL,NULL,NULL,NULL); //display your buffer on screen
  121.                 TranslateMessage(&msg); //translate the msg of the GetMessage of your while loop
  122.                 DispatchMessage(&msg); //dispath the msg of the GetMessage of your while loop
  123.         }
  124.         CleanUp(); //call your CleanUp() function to prevent memory leak
  125.         return 0; //return 0 no problem
  126. }
  127.  

4
DirectX / D3D9 Tutorial 1: Hello world
« on: March 06, 2010, 09:41:15 am »
My first d3d9 tutorial, drawing Hello World


Code: C++
  1. #include <windows.h> //include windows header for some function like MessageBox, creating the window.
  2. #include "d3dx9.h" //include a directx header
  3. #include <stdio.h> //for the sprinf_s function used by DrawString
  4.  
  5. #pragma comment(lib, "d3dx9.lib") //link the library
  6. #pragma comment(lib, "d3d9.lib") //link the library
  7. #define Emsg(msg){MessageBox(NULL,msg,"Error",MB_OK|MB_ICONEXCLAMATION);} //macro for error pop-up
  8.  
  9. int WINDOW_WIDTH = 1024; //window width
  10. int WINDOW_HEIGHT = 768; //window height
  11. bool windowed = true; //window mode, change to false for full screen
  12.  
  13. IDirect3D9 *pD3D; //global variable that will be used by a couple of our function
  14. IDirect3DDevice9 *pDevice; //a device that will be used for most of our function created inside *pD3D
  15. LPD3DXFONT pFont; //font variable to use with our create font function and to display text after
  16.  
  17. int textx = 482; //text x coord
  18. int texty = 378; //text y coord
  19. LRESULT CALLBACK wndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) //callback function for our GetMessage function on the while statement inside the main function
  20. {
  21.         switch(uMsg) //switch the MSG variable passed
  22.         {
  23.         case WM_CLOSE: //case it's a Window Close MSG
  24.                 PostQuitMessage(0); //Apply a Quit Message
  25.                 break;
  26.         }
  27.         return DefWindowProc(hWnd,uMsg,wParam,lParam); //pass the variable
  28. }
  29.  
  30. HRESULT initialize() //funciton where all the initialization stuff go
  31. {        //change the parameter (LPCSTR)"Arial" to any other font name in your font folder to test other font
  32.         if(FAILED(D3DXCreateFont(pDevice, 15, 0, FW_BOLD, 1, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, (LPCSTR)"Arial", &pFont))) //create a font in our Device with the pFont variable
  33.         {
  34.                 Emsg("Failed to create the font"); //error pop-up for debug purpose
  35.                 return E_FAIL; //return it failed
  36.         }
  37. }
  38.  
  39. void DrawString(int x, int y, DWORD color, LPD3DXFONT g_pFont, const char *fmt) //function to draw text won't go in detail in this tutorial
  40. {
  41.         RECT FontPos = { x, y, x + 120, y + 16 };
  42.         char buf[1024] = {'\0'};
  43.         va_list va_alist;
  44.  
  45.         va_start(va_alist, fmt);
  46.         vsprintf_s(buf, fmt, va_alist);
  47.         va_end(va_alist);
  48.         g_pFont->DrawText(NULL, buf, -1, &FontPos, DT_NOCLIP, color);
  49. }
  50.  
  51. HRESULT render() //function where all Drawing/Render stuff go
  52. {
  53.         if(SUCCEEDED(pDevice->BeginScene())) //Call the BeginScene function with our Device and see if it succeeded, all drawing/render code go behind BeginScene and EndScene
  54.         {       //first parameter is the x coord of the text we use our global variable textx, second parameter is samething but with y, last parameter is the text to draw in this case Hello World
  55.                 DrawString(textx, texty, D3DCOLOR_ARGB(255, 0, 255, 0), pFont, "Hello World"); //if it did draw Hello world on buffer, D3DCOLOR_ARGB(255, 0, 255, 0) is the color the first parametter is the alpha (transparent),rest is Red Blue Green the total of red blue green must be 255 maximum
  56.                 pDevice->EndScene(); //Call the EndScene function with our Device
  57.                 return S_OK; //return it succeeded
  58.         }
  59.         return E_FAIL; //return it failed
  60. }
  61.  
  62. void CleanUp() //function to delete/release things to prevent memory leak
  63. {
  64.         if(pD3D) //check if pD3D ism't released
  65.                 pD3D->Release(); //release it
  66.         if(pDevice) //check if pDevice ism't released
  67.                 pDevice->Release(); //release it
  68.         if(pFont) //check if pFont ism't released
  69.                 pFont->Release(); //release it
  70. }
  71.  
  72. int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) //our main function the first function called of the program
  73. {
  74.         WNDCLASSEX wc; //window class won't go in detail not related to this tutorial really
  75.         wc.cbSize = sizeof(WNDCLASSEX);
  76.         wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  77.         wc.lpfnWndProc = (WNDPROC)wndProc;
  78.         wc.cbWndExtra = 0;
  79.         wc.cbClsExtra = 0;
  80.         wc.hInstance = hInstance;
  81.         wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  82.         wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  83.         wc.hbrBackground = NULL;
  84.         wc.lpszMenuName = NULL;
  85.         wc.lpszClassName = "D3DTEST"; //class name
  86.         wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
  87.  
  88.         RECT rect; //window rectangle
  89.         rect.top = (long)0;
  90.         rect.left = (long)0;
  91.         rect.right = WINDOW_WIDTH; //use our global WINDOW_WIDTH variable
  92.         rect.bottom = WINDOW_HEIGHT; //use our global WINDOW_HEIGHT variable
  93.  
  94.         if(!RegisterClassEx(&wc)) //register the window cs
  95.         {
  96.                 Emsg("Could not register window class"); //error pop-up for debug purpose
  97.                 return 1; //return error
  98.         }
  99.  
  100.         AdjustWindowRectEx(&rect,WS_OVERLAPPEDWINDOW,false,WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); //set the window width and height with the rect above
  101.         //the D3DTEST must match the class name of the window class and D3D TEST is the window name
  102.         HWND hWindow = CreateWindowEx(NULL,"D3DTEST","D3D TEST",WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,0,0,rect.right-rect.left,rect.bottom-rect.top,NULL,NULL,hInstance,NULL); //create the window
  103.  
  104.         if(!hWindow) //if the window failed to create
  105.         {
  106.                 DestroyWindow(hWindow); //destroy the window
  107.                 UnregisterClass("D3DTEST",hInstance); //unregister our window class
  108.                 Emsg("Failed to create the window"); //error pop-up for debug purpose
  109.                 return 1; //return error
  110.         }
  111.  
  112.         ShowWindow(hWindow,SW_SHOW); //show our window
  113.         UpdateWindow(hWindow); //update our window
  114.         SetForegroundWindow(hWindow); //set our window on top
  115.         SetFocus(hWindow); //set the focus on our window
  116.  
  117.         D3DPRESENT_PARAMETERS d3dpp; //the presentation parameters that will be used when we will create the device
  118.         ZeroMemory(&d3dpp,sizeof(d3dpp)); //to be sure d3dpp is empty
  119.         d3dpp.Windowed = windowed; //use our global windowed variable to tell if the program is windowed or not
  120.         d3dpp.hDeviceWindow = hWindow; //give the window handle of the window we created above
  121.         d3dpp.BackBufferCount = 1; //set it to only use 1 backbuffer
  122.         d3dpp.BackBufferWidth = WINDOW_WIDTH; //set the buffer to our window width
  123.         d3dpp.BackBufferHeight = WINDOW_HEIGHT; //set the buffer to out window height
  124.         d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; //the backbuffer format
  125.         d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; //SwapEffect
  126.  
  127.         pD3D = Direct3DCreate9(D3D_SDK_VERSION); //Create the presentation parameters
  128.  
  129.         if(FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWindow,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&pDevice))) //create the device and check if it failed
  130.         {
  131.                 Emsg("Failed to create device"); //error pop-up for debug purpose
  132.                 CleanUp(); //call your CleanUp() function to prevent memory leak
  133.                 return 1; //exit the program return 1 error
  134.         }
  135.  
  136.         if(FAILED(initialize())) //call the initialize function and check if it failed
  137.         {
  138.                 Emsg("Failed to initialize"); //error pop-up for debug purpose
  139.                 CleanUp(); //call your CleanUp() function to prevent memory leak
  140.                 return 1; //exit the program return 1 error
  141.         }
  142.  
  143.         MSG msg; //declare a MSG local variable for the GetMessage of the while loop
  144.         while(GetMessage(&msg,NULL,0,0)) //GetMessage reffer to the wndProc() function
  145.         {
  146.                 pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1.0f,0.0f); //Clear the screen with black, basically since we only draw text here it's like your background change the D3DCOLOR_XRGB(0,0,0) to change the color the 3 number additioned must make 255 maximum
  147.                 if(FAILED(render())) //call the function render() and verify if it worked
  148.                 {
  149.                         Emsg("Render failed"); //error pop-up for debug purpose
  150.                 }
  151.  
  152.                 pDevice->Present(NULL,NULL,NULL,NULL); //display your buffer on screen
  153.                 TranslateMessage(&msg); //translate the msg of the GetMessage of your while loop
  154.                 DispatchMessage(&msg); //dispath the msg of the GetMessage of your while loop
  155.         }
  156.         CleanUp(); //call your CleanUp() function to prevent memory leak
  157.         return 0; //return 0 no problem
  158. }
  159.  

5
OpenGL / sprite object
« on: December 26, 2009, 12:44:06 pm »
Ok i'm making a game and each of my map , have a background and object like platform loaded from a file

the file look like this
map1.map
Code: [Select]
1 200:200 1:11 = object total number
200 = x position on map
200 = y position on map
1 = objid to know what sprite to load
1 = object type

so in this exampel there is only 1 object

here my function to load object its not completely done yet
Code: C++
  1. void LoadMap(int mapid)
  2. {
  3.         char mapbg[200];
  4.         char mapfile[200];
  5.         char objsurpath[200];
  6.         sprintf(mapfile,"C:\\Users\\powerfear\\Documents\\Visual Studio 2010\\Projects\\game\\Debug\\data\\map\\map%d.map",mapid); //full path to test in debug with visual studio
  7.         sprintf(mapbg,"C:\\Users\\powerfear\\Documents\\Visual Studio 2010\\Projects\\game\\Debug\\data\\image\\background\\map%d.bmp",mapid);
  8.         sprintf(objsurpath,"C:\\Users\\powerfear\\Documents\\Visual Studio 2010\\Projects\\game\\Debug\\data\\image\\sprite\\map%d.bmp",mapid);
  9.         objsurface = SDL_LoadBMP(objsurpath);
  10.     int y,objx,objy;
  11.     FILE *fp;
  12.     fp = fopen(mapfile, "rb");
  13.         if (fp == NULL){
  14.         exit(1);
  15.         }
  16.         fscanf(fp,"%d",&objnum);
  17.     for (y=0;y<=objnum;y++) //get info of all object
  18.     {
  19.                 objx = 0;
  20.                 objy = 0;
  21.                 fscanf(fp,"%d:%d",&objx,&objy);
  22.                 fscanf(fp,"%d:%d",&objid[objx][objy],&objtype[objx][objy]); //put the vlaue on a big int array only way i could think of..
  23.                 //apply_surface(objx,objy,objsurface,screen); //tested to see if i could just apply 1 time but it dissapear directly because of main game loop
  24.     }
  25.     fclose(fp);
  26.         if(fopen(mapbg, "rb") == NULL){
  27.                 exit(1);
  28.         }
  29.         backgrd = SDL_LoadBMP(mapbg);
  30.         backgrd = SDL_DisplayFormat(backgrd);
  31. }
  32.  

Here are the variable they are global variable
int objnum = 0;
int objid[MAP_WIDTH][MAP_HEIGHT];
int objtype[MAP_WIDTH][MAP_HEIGHT];

my map are quite big 1000x4000
the map surface is called "screen"
and i'm using a rectangle "camera" for the scrolling

the background is draw each loop like this
apply_surface(0,0,backgrd,screen,&camera);
0 = x | 0 = y | backgrd = background surface that is set in load map | screen where to apply background | &camera

then i draw the character
apply_surface(rcSprite.x - camera.x, rcSprite.y - camera.y, mychar, screen);
think you can understand with the background example

but now i would need to load each object but i dunno how going trough the complete array would be quite long and useless

6
C++ / weird problem/bug
« on: November 17, 2009, 11:48:02 am »
i messed with the CelesetialKey's chat client/server to use it as an login server for my emulator (still not complete)

with the last change i made, it made a kind of bug the .exe was 17kb before the change and after when i compile it is 1.86GB (yes you read it correctly)!!!

and the .exe dont even work, the change i made didn't added any new include only added SendGlobal function, the 3 SendData function, changed them to work with byte and made SendGlobal send to custom client, also added SendGlobal to the NetworkEngine.h to be able to use on the NetworkEngine.cpp i also added a BYTE variable and placed a SendGloval that send that variable in one of the function in the NetworkEngine.cpp

i dunno why but as i said after that it went to 1.86GB (was wondering why it was so long to compile -.-) and it don't even work...

here my file

NetworkEngine.h
Code: C++
  1. #include <winsock2.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. //#pragma pack
  6. #define MAX_SIZE         999999999
  7. #define CLIENT_LIST_SIZE   9999999
  8.  
  9. // Keeps track of all sockets
  10. extern SOCKET ID[CLIENT_LIST_SIZE];
  11.  
  12.  
  13. // Packet Structure will make later
  14. struct Message
  15. {
  16.    char   Name[MAX_SIZE];
  17.    char   Data[MAX_SIZE];
  18.    int      ID;
  19. };
  20.  
  21. // Required Handlers
  22. void HandleMessageStruct(Message msg, SOCKET socket);
  23. void SendGlobal(BYTE packet, int x);
  24. //**************************************
  25.  
  26.  
  27. class NetworkEngine
  28. {
  29. private:
  30.    bool      _IsServer;
  31.    int         TotalConnected;
  32.    // Server Variables
  33.    SOCKET      ServSock;
  34.    int         ServPort;
  35.    WSAData      wsaData;
  36.    struct      sockaddr_in server;
  37.    HANDLE      Hthread;
  38.    HANDLE      Hmutex;
  39.    FD_SET      masterSet;
  40.    timeval      waitTime;
  41.  
  42.    bool      gQuitFlag;
  43.  
  44.    static int   _threadstartS(void *param);
  45.    static int   _threadstartC(void *param);
  46.    void      ServerAcceptingThread();
  47.    void      ClientRecvThread();
  48.  
  49.    // Client Variables
  50.    WSAData      Client_wsaData;
  51.    SOCKET      Sock;
  52.    struct      hostent *host_entry;
  53.    struct      sockaddr_in client;
  54.  
  55.    int         StartClient(unsigned short Port, const char* Address);
  56.  
  57. public:
  58.    // Constructor SERVER
  59.    NetworkEngine(int Port);
  60.    // Constructor CLIENT
  61.    NetworkEngine(unsigned short Port, const char* Address);
  62.  
  63.  
  64.    // SERVER Functions
  65.    int         StartServer();
  66.    SOCKET      GetServSocket()            {   return ServSock;   };
  67.    void      SetServSocket(SOCKET sSock)   {   ServSock = sSock;   };
  68.    HANDLE      GetMutexHandle()         {   return Hmutex;      };
  69.    HANDLE      GetThreadHandle()         {   return Hthread;      };
  70.    void      HoldMutex(bool Hold = false);
  71.    bool      IsQuit()               {   return gQuitFlag;   };
  72.    void      SetQuit(bool Q)            {   gQuitFlag = Q;      };
  73.    void      GoListen(Message Data);
  74.    SOCKET      SendData(BYTE Data, SOCKET Socket);
  75.    void      EndServer();
  76. //   bool      IsServer()               {   return _IsServer;   };
  77.  
  78.    // CLIENT Functions
  79.    void      EndClient();
  80.    SOCKET      GetSocket()               {   return Sock;   };
  81.    SOCKET      SendData(char DataSize[MAX_SIZE]);
  82.    SOCKET      SendData(struct Message Data);
  83.    Message      ReceiveData(SOCKET socket);
  84.  
  85.    // Get Next Free ID
  86.    SOCKET      GetNextFreeSlot();
  87.    int         AddID(SOCKET socket);
  88.    int         RemoveID(SOCKET socket);
  89.    int         GetTotalConnected()         {   return TotalConnected;   };
  90. };

NetworkEngine.cpp
Code: C++
  1. #include "NetworkEngine.h"
  2. #define FREE -999
  3. BYTE EntryPkt[21] = {0x00,0xAA,0x02,0x0B,0x00,0xC4,0x09,0x00,0x00,0x64,0x00,0x00,0x00,0xE6,0x02,0x00,0x00,0x01,0x02,0x03,0x04};
  4. SOCKET ID[CLIENT_LIST_SIZE];
  5. SOCKET NetworkEngine::GetNextFreeSlot()
  6. {
  7.    for(int x=0; x<CLIENT_LIST_SIZE; x++)
  8.    {
  9.       if(ID[ x ] == FREE)
  10.       {
  11.          cout << "ID["<<x<<"] is free.\n";
  12.          return x;
  13.       }
  14.    }
  15.    return CLIENT_LIST_SIZE;
  16. }
  17. int NetworkEngine::AddID(SOCKET socket)
  18. {
  19.    ID[GetNextFreeSlot()] = socket;   // set the clients socket to the next free slot
  20.    TotalConnected++;
  21.    return 0;
  22. }
  23. int NetworkEngine::RemoveID(SOCKET socket)
  24. {
  25.    return 0;
  26. }
  27. NetworkEngine::NetworkEngine(int Port)
  28. {
  29.    for(int x=0; x<CLIENT_LIST_SIZE; x++)
  30.       ID[ x ]   = FREE;
  31.    TotalConnected = 0;
  32.    _IsServer   = true;
  33.    ServPort   = Port;
  34.    gQuitFlag   = false;
  35.    waitTime.tv_sec      = 0; // Set it to 0
  36.    waitTime.tv_usec   = 0; // Set it to 0
  37.    FD_ZERO(&masterSet);
  38.    StartServer();
  39. }
  40. int NetworkEngine::StartServer()
  41. {
  42.    Hmutex = CreateMutex(NULL, false, NULL);
  43.    int error;
  44.    if ((error = WSAStartup(MAKEWORD(2, 2), &wsaData)) == SOCKET_ERROR)
  45.    {
  46.       cout << "server: Winsock failed to start.\n";
  47.       return -1;
  48.    }
  49.    ServSock = socket(AF_INET, SOCK_STREAM, 0);
  50.    if (ServSock == SOCKET_ERROR)
  51.    {
  52.       cout << "server: Unable to create socket;\n";
  53.       return -1;
  54.    }
  55.    server.sin_family = AF_INET;
  56.    server.sin_port = htons(ServPort);
  57.    server.sin_addr.s_addr = INADDR_ANY;
  58.    if (bind(ServSock, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
  59.    {
  60.       cout << "server: Binding failed.\n";
  61.       closesocket(ServSock);
  62.       return -1;
  63.    }
  64.    if (listen(ServSock, 5) == SOCKET_ERROR)
  65.    {
  66.       cout << "server: Listening failed.\n";
  67.       closesocket(ServSock);
  68.       return -1;
  69.    }
  70.    cout << "server: Login server started.\n";
  71.    int threadID;
  72.    Hthread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&_threadstartS, this, 0, (LPDWORD)&threadID);
  73.    return 0;
  74. }
  75. int NetworkEngine::_threadstartS(void *param)
  76. {
  77.    ((NetworkEngine*)param)->ServerAcceptingThread();
  78.    return 0;
  79. }
  80. void NetworkEngine::ServerAcceptingThread()
  81. {
  82.    int mySocket = ServSock;
  83.    for ( ; ; )
  84.    {
  85.       unsigned int clientSocket = accept(mySocket, 0, 0);  
  86.       if (clientSocket == SOCKET_ERROR)
  87.       {
  88.                   cout << "server: Unable to accept socket.\n";
  89.          gQuitFlag = true;
  90.          return;
  91.       }
  92.       else
  93.       {
  94.          WaitForSingleObject(Hmutex, INFINITE);
  95.          FD_SET(clientSocket, &masterSet);
  96.          AddID(clientSocket);
  97.          ReleaseMutex(Hmutex);
  98.                  cout << "server: Client on " << clientSocket <<" connected.\n" << endl;
  99.                  SendGlobal(EntryPkt[21],clientSocket);
  100.       }
  101.    }
  102.       return;
  103. }
  104. void NetworkEngine::EndServer()
  105. {
  106.    WaitForSingleObject(Hthread, INFINITE);// Kill thread and handle
  107.    CloseHandle(Hthread);
  108.    CloseHandle(Hmutex);
  109.    closesocket(ServSock);
  110.    WSACleanup();
  111.    cout << "server: Shutting down...\n";
  112. }
  113. void NetworkEngine::HoldMutex(bool Hold)
  114. {
  115.    if(Hold)
  116.       WaitForSingleObject(Hmutex, INFINITE);
  117.    else
  118.       ReleaseMutex(Hmutex);
  119. }
  120. void NetworkEngine::GoListen(Message Data)
  121. {
  122.    for ( ; ; )
  123.    {
  124.       if (IsQuit())
  125.       {
  126.          break;
  127.       }
  128.       HoldMutex(true);
  129.       FD_SET TempSet = masterSet;
  130.       HoldMutex(false);
  131.       if (TempSet.fd_count == 0)
  132.       {
  133.          continue;
  134.       }
  135.       int result = select(TempSet.fd_count, &TempSet, NULL, NULL, &waitTime); // Select a socket in out TempSet
  136.       //
  137.       //
  138.       if (result == 0) // Check for 0's agian
  139.       {
  140.          continue; // = Empty
  141.       }
  142.       if (result == SOCKET_ERROR)
  143.       {
  144.                   cout << "server: Select Macro has failed.\n";
  145.          continue;
  146.       }
  147.       for (unsigned int i = 0; i < TempSet.fd_count; i++)
  148.       {
  149.          unsigned int clientSocket = TempSet.fd_array[ i ];
  150.          int nBytes;
  151.          unsigned long messageSize;
  152.          nBytes = recv(clientSocket, (char*)&messageSize, sizeof(messageSize), 0);
  153.          if (nBytes == SOCKET_ERROR)
  154.          {
  155.             int error = WSAGetLastError();
  156.             if (error == WSAECONNRESET)
  157.             {
  158.                HoldMutex(true);
  159.                FD_CLR(clientSocket, &masterSet);
  160.                RemoveID(clientSocket);
  161.                HoldMutex(false);            
  162.                closesocket(clientSocket);              
  163.                            cout << "server: Client on "<< clientSocket << " has Disconnected." << endl;
  164.                continue;
  165.             }
  166.             else
  167.             {
  168.                                 cout << "server: Unrecoverable error has occured, shutting down.\n";
  169.                SetQuit(true);
  170.                break;
  171.             }
  172.          }
  173.          if (nBytes == 0)
  174.          {
  175.             HoldMutex(true);
  176.             FD_CLR(clientSocket, &masterSet);
  177.             RemoveID(clientSocket);
  178.             HoldMutex(false);
  179.             closesocket(clientSocket);            
  180.                         cout << "server: Client on " << clientSocket << " has disconnected" << "\n";
  181.             Sleep(1000);
  182.             continue;
  183.          }
  184.          messageSize = ntohl(messageSize);
  185.          nBytes = recv(clientSocket, (char*)&Data, messageSize, 0); // buffer
  186.          if (nBytes == SOCKET_ERROR)
  187.          {
  188.                          cout << "server: Socket data caused an error.\n";
  189.             SetQuit(true);
  190.             EndServer();
  191.          }
  192.          HandleMessageStruct(Data, clientSocket);
  193.       }
  194.    }
  195. }
  196. Message NetworkEngine::ReceiveData(SOCKET socket)
  197. {
  198.    int nBytes;
  199.    Message temp;
  200.    unsigned long messageSize;
  201.    nBytes = recv(socket, (char*)&messageSize, sizeof(messageSize), 0);
  202.    messageSize = ntohl(messageSize);
  203.    nBytes = recv(socket, (char*)&temp, messageSize, 0); // buffer
  204.    return temp;
  205. }
  206. SOCKET   NetworkEngine::SendData(char buffer[])
  207. {
  208.    int nBytes;
  209.    unsigned long messageSize = strlen(buffer);
  210.    messageSize = htonl(messageSize);
  211.    if ((nBytes = send(Sock, (char*)&messageSize, sizeof(messageSize), 0)) == SOCKET_ERROR)
  212.    {
  213.       cout << "Client: Sending data size has failed.\n";
  214.       return SOCKET_ERROR;
  215.    }
  216.    messageSize = ntohl(messageSize);
  217.    if ((nBytes = send(Sock, buffer, messageSize, 0)) == SOCKET_ERROR)
  218.    {
  219.       cout << "Client: Sending data has failed.\n";
  220.       return SOCKET_ERROR;
  221.    }
  222.    cout << "\n>";
  223.    return 0;
  224. }
  225. SOCKET   NetworkEngine::SendData(struct Message Data)
  226. {
  227.    int nBytes;
  228.    unsigned long messageSize = sizeof(Data);
  229.    messageSize = htonl(messageSize);
  230.    if ((nBytes = send(Sock, (char*)&messageSize, sizeof(messageSize), 0)) == SOCKET_ERROR)
  231.    {
  232.       cout << "server: Sending data size has failed.\n";
  233.       return SOCKET_ERROR;
  234.    }
  235.    messageSize = ntohl(messageSize);
  236.    if ((nBytes = send(Sock, (char*)&Data, messageSize, 0)) == SOCKET_ERROR)
  237.    {
  238.       cout << "server: Sending data has failed.\n";
  239.       return SOCKET_ERROR;
  240.    }
  241.    cout << "\n>";
  242.    return 0;
  243. }
  244. SOCKET   NetworkEngine::SendData(BYTE Data, SOCKET Socket)
  245. {
  246.    int nBytes;
  247.    unsigned long messageSize = sizeof(Data);
  248.    messageSize = htonl(messageSize);
  249.    if ((nBytes = send(Socket, (char*)&messageSize, sizeof(messageSize), 0)) == SOCKET_ERROR)
  250.    {
  251.       cout << "server: Sending data size has failed.\n";
  252.       return SOCKET_ERROR;
  253.    }
  254.    messageSize = ntohl(messageSize);
  255.    if ((nBytes = send(Socket, (char*)&Data, messageSize, 0)) == SOCKET_ERROR)
  256.    {
  257.       cout << "server: Sending data has failed.\n";
  258.       return SOCKET_ERROR;
  259.    }
  260.    cout << "\n>";
  261.    return 0;
  262. }

ExampleMain.cpp
Code: C++
  1. #include "NetworkEngine.h"
  2. NetworkEngine *server;
  3. Message Datas = {   "E.M.M.Y",
  4.                "Hello there!",
  5.                1}; //will replace by 12sky2 packet
  6. int main()
  7. {
  8.    cout << "Server: Starting...\n";
  9.    server = new NetworkEngine(11091);
  10.    //
  11.    for(int x=0; x<server->GetTotalConnected(); x++)
  12.    {
  13.       cout << "Current Values: " << ID[ x ] << endl;
  14.    }
  15.    //
  16.    if (server->GetMutexHandle() == NULL)
  17.    {
  18.       cout << "server: Unable to create mutex.\n";
  19.       server->EndServer();
  20.       return 1;
  21.    }
  22.    if (server->GetThreadHandle() == NULL)
  23.    {
  24.       cout << "server: Unable to start accepting.\n";
  25.       server->EndServer();
  26.       return 1;
  27.    }
  28.    Sleep(100);
  29.    //
  30.    ///
  31.    ////
  32.    server->GoListen(Datas);
  33.    ////
  34.    ///
  35.    //
  36.    server->EndServer();
  37.    cout << "server: Press any key to shut down...\n";
  38.    getchar();
  39.    return 0;
  40. }
  41. void HandleMessageStruct(Message msg, SOCKET ClientSocket)
  42. {
  43. //going to code later
  44. }
  45. void SendGlobal(BYTE packet, int x)
  46. {
  47.         cout << "server: Sending to: " << ID[ x ] << endl;
  48.         int err = server->SendData(packet, ID[ x ]);
  49.         if(err == SOCKET_ERROR)
  50.            cout << "server: Failed to send to client("<<x<<")\n";
  51. }
  52.  

7
Challenges / Hackmeh
« on: November 14, 2009, 04:26:27 pm »
I made this little thing in C++

Goal is to get your health to 250 only by memory editing, code injection , reverse engineering and etc not allowed ^^


8
C++ / server / client related
« on: November 13, 2009, 04:52:17 pm »
Hello,

I'm wondering a few things so if any of those pro in C++ could help me  :D

Could you make a simple server / client server example for once you start the server it read some value from a file like a .ini and set some variable then each time a client connect it send those variable to the client to set the variable on the client.

Also optionally adding a command like /refresh that we can send from client to server that would make server read the value again and return back the variable, because server won't read up value each time a client connect but only once it start.

The chat client / server made by CelestialKey gave me a good idea of how server / client work in C++ but i just want another example to clarify things up ;P

Pages: [1]

Donate


* Search


* Recent Posts

Image Comparison by Shishka
[May 15, 2017, 01:18:02 pm]


Re: srchub - free source code hosting by Nathan
[December 14, 2015, 11:37:02 pm]


Re: srchub - free source code hosting by Celestialkey
[November 27, 2015, 08:51:42 am]


Updates by Nathan
[October 30, 2015, 08:27:36 pm]


Re: Client-Server Messaging by Nathan
[October 25, 2015, 05:48:57 pm]