### Startup Command Example Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/consoleserver.html This snippet demonstrates how to start the server with specific parameters, including port, max connections, and socket descriptor. It utilizes the ReturnResult function to provide feedback. ```C++ if (strcmp(command, "Startup")==0) { SocketDescriptor socketDescriptor((unsigned short)atoi(parameterList[1]), parameterList[3]); ReturnResult(peer->Startup((unsigned short)atoi(parameterList[0]), atoi(parameterList[2]), &socketDescriptor, 1), command, transport, systemAddress); } ``` -------------------------------- ### Previewing Install Targets Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jpeg-7/install.txt Use 'make -n install' to see the installation targets before executing 'make install'. This helps verify where files will be placed. ```bash make -n install ``` -------------------------------- ### CMake Project Setup Source: https://github.com/slikesoft/slikenet/blob/master/Samples/AutopatcherClient/CMakeLists.txt Initializes the CMake build system and sets the project name. This is a standard starting point for CMake projects. ```cmake cmake_minimum_required(VERSION 2.6) project(AutopatcherClient) ``` -------------------------------- ### Install Visual Studio Add-in Source: https://github.com/slikesoft/slikenet/blob/master/Samples/nacl_sdk/RakNet_NativeClient/HowToSetup.txt Install the Visual Studio add-in for Native Client development. This involves running the install script after navigating to the add-in directory. ```bash D:\nacl_sdk>naclsdk install vs_addin D:\nacl_sdk>cd vs_addin D:\nacl_sdk\vs_addin>install.bat ``` -------------------------------- ### Linux Server Build Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Commands to install dependencies and compile the RakNet chat example server on a Linux system. ```bash sudo apt-get install wget sudo apt-get update sudo apt-get install --fix-missing g++ sudo apt-get install gdb cd RakNet_Install_Directory/Source g++ -m64 -g -pthread -I./ "../Samples/Chat Example/Chat Example Server.cpp" *.cpp ./a.out ``` -------------------------------- ### Build 64-bit Chat Example Server (Linux) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Command to compile the 64-bit chat example server on Linux using g++. ```bash g++ -m64 -g -lpthread -I./ "../Samples/Chat Example/Chat Example Server.cpp" *.cpp ``` -------------------------------- ### Installation Rules (Non-Windows) Source: https://github.com/slikesoft/slikenet/blob/master/Lib/LibStatic/CMakeLists.txt This section defines the installation rules for non-Windows platforms. It installs the static library, configuration files, and header files to their respective locations. ```cmake configure_file(../../slikenet-config-version.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/slikenet-config-version.cmake @ONLY) INSTALL(TARGETS SLikeNetLibStatic EXPORT SLikeNetLibStatic DESTINATION lib/slikenet-${SLikeNet_VERSION}) INSTALL(FILES ${ALL_COMPATIBILITY_HEADER_SRC} DESTINATION include/slikenet-${SLikeNet_VERSION}) INSTALL(FILES ${ALL_COMPATIBILITY_HEADER_SRC_2} DESTINATION include/slikenet-${SLikeNet_VERSION}/slikenet) INSTALL(FILES ${ALL_HEADER_SRCS} DESTINATION include/slikenet-${SLikeNet_VERSION}/include/slikenet) INSTALL(FILES ../../slikenet-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/slikenet-config-version.cmake DESTINATION lib/slikenet-${SLikeNet_VERSION}) INSTALL(EXPORT SLikeNetLibStatic FILE slikenet.cmake DESTINATION lib/slikenet-${SLikeNet_VERSION}) ``` -------------------------------- ### Basic Unix Installation Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jpeg-7/install.txt Standard commands for configuring, building, testing, and installing the JPEG library on a Unix-like system. ```bash ./configure make make test make install ``` -------------------------------- ### Instantiate and Destroy RakNet Peer Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/tutorialsample1.html This C++ code shows how to get an instance of RakPeerInterface, start it up as either a client or a server based on user input, and then destroy the instance. It's the basic setup for any RakNet application. ```C++ #include #include "RakPeerInterface.h" #define MAX_CLIENTS 10 #define SERVER_PORT 60000 int main(void) { char str[512]; RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance(); bool isServer; printf("(C) or (S)erver?\n"); gets(str); if ((str[0]=='c')||(str[0]=='C')) { RakNet::SocketDescriptor sd; peer->Startup(1,&sd, 1); isServer = false; } else { RakNet::SocketDescriptor sd(SERVER_PORT,0); peer->Startup(MAX_CLIENTS, &sd, 1); isServer = true; } // TODO - Add code body here RakNet::RakPeerInterface::DestroyInstance(peer); return 0; } ``` -------------------------------- ### UDP Proxy Coordinator Setup Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/natpunchthrough.html Basic setup for the UDPProxyCoordinator plugin, including instantiation, attachment to RakPeerInterface, and setting a login password. ```C++ UDPProxyCoordinator udpProxyCoordinator; rakPeer->AttachPlugin(&udpProxyCoordinator); udpProxyCoordinator.SetRemoteLoginPassword(COORDINATOR_PASSWORD); ``` -------------------------------- ### Example Quantization Table File Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jpeg-7/wizard.txt This example file defines two quantization tables (luminance and chrominance) in a format compatible with cjpeg's -qtables switch. Comments are supported. ```text # Quantization tables given in JPEG spec, section K.1 # This is table 0 (the luminance table): 16 11 10 16 24 40 51 61 12 12 14 19 26 58 60 55 14 13 16 24 40 57 69 56 14 17 22 29 51 87 80 62 18 22 37 56 68 109 103 77 24 35 55 64 81 104 113 92 49 64 78 87 103 121 120 101 72 92 95 98 112 100 103 99 # This is table 1 (the chrominance table): 17 18 24 47 99 99 99 99 18 21 26 66 99 99 99 99 24 26 56 99 99 99 99 99 47 66 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 ``` -------------------------------- ### Install g++ (Alternative Debian/Ubuntu) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Alternative command to install g++ on Debian-based systems. ```bash sudo apt-get update sudo apt-get install g++ ``` -------------------------------- ### Install wget (Debian/Ubuntu) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Command to install wget, a utility for downloading files from the web, on Debian-based systems. ```bash sudo apt-get install wget ``` -------------------------------- ### Rackspace API Setup and Authentication Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/rackspaceinterface.html This snippet shows the basic setup for the Rackspace interface, including initializing TCPInterface and authenticating with Rackspace using username and API key. ```APIDOC ## Rackspace API Setup and Authentication ### Description Initializes the TCPInterface and Rackspace classes, then authenticates with Rackspace using a provided authentication URL, username, and API key. It also includes a loop to process incoming network packets and connection events. ### Setup Code ```cpp #include "Rackspace.h" #include "TCPInterface.h" RakNet::Rackspace rackspaceApi; RakNet::TCPInterface tcpInterface; RakNet::RackspaceEventCallback_Default callback; tcpInterface.Start(0, 0, 1); rackspaceAPI.Authenticate(&tcpInterface, "myAuthURL", "myRackspaceUsername", "myRackspaceAPIKey"); while (1) { for (RakNet::Packet *packet=tcpInterface.Receive(); packet; tcpInterface.DeallocatePacket(packet), packet=tcpInterface.Receive()) rackspaceApi.OnReceive(packet); rackspaceApi.OnClosedConnection(tcpInterface.HasLostConnection()); } ``` ### Authentication Parameters - **tcpInterface**: A pointer to the initialized RakNet::TCPInterface instance. - **myAuthURL**: The URL for Rackspace authentication. - **myRackspaceUsername**: Your Rackspace username. - **myRackspaceAPIKey**: Your Rackspace API key. ### Callback Upon successful authentication, a callback `OnAuthenticationResult` will be triggered with `eventType` set to `RET_Success_204`. ``` -------------------------------- ### Start Dual IPV4 and IPV6 Sockets Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/ipv6support.html This code snippet demonstrates how to start a RakNet server with support for both IPV4 and IPV6. It includes a fallback mechanism to start with IPV4 only if IPV6 is not supported. ```cpp RakNet::SocketDescriptor socketDescriptors[2]; socketDescriptors[0].port=atoi(portstring); socketDescriptors[0].socketFamily=AF_INET; // Test out IPV4 socketDescriptors[1].port=atoi(portstring); socketDescriptors[1].socketFamily=AF_INET6; // Test out IPV6 bool b = server->Startup(4, socketDescriptors, 2 )==RakNet::RAKNET_STARTED; server->SetMaximumIncomingConnections(4); if (!b) { printf("Failed to start dual IPV4 and IPV6 ports. Trying IPV4 only.\n"); // Try again, but leave out IPV6 b = server->Startup(4, socketDescriptors, 1 )==RakNet::RAKNET_STARTED; if (!b) { puts("Server failed to start. Terminating."); exit(1); } } ``` -------------------------------- ### Setup Receive for FileListTransfer Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/filelisttransfer.html Server-side setup to receive files. Call this to allow a system to send files and specify a callback handler for incoming data. ```C++ void SetupReceive(SystemAddress systemAddress, FileListTransferCBInterface *callback); ``` -------------------------------- ### Rackspace API Response Example (List Images) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/rackspaceinterface.html An example of the HTTP response received after a successful 'ListImages' call, detailing the structure of the returned XML. ```http HTTP/1.1 200 OK Server: Apache-Coyote/1.1 vary: Accept, Accept-Encoding, X-Auth-Token Last-Modified: Tue, 29 Mar 2011 22:41:36 GMT X-PURGE-KEY: /570016/images Cache-Control: s-maxage=1800 Content-Type: application/xml Content-Length: 1334 Date: Sat, 02 Apr 2011 15:15:19 GMT X-Varnish: 601046147 Age: 0 Via: 1.1 varnish Connection: keep-alive ``` -------------------------------- ### Minimal SQLiteClientLoggerPlugin TCP Setup Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/sqlite3loggerplugin.html Illustrates a basic client-side setup for the SQLiteClientLoggerPlugin using PacketizedTCP. This connects to a specified server and sets the parameters for logging. ```C++ PacketizedTCP packetizedTCP; RakNet::SQLiteClientLoggerPlugin loggerPlugin; packetizedTCP.AttachPlugin(&loggerPlugin); packetizedTCP.Start(0,0); SystemAddress serverAddress = packetizedTCP.Connect("127.0.0.1", 38123, true); // Assuming connection completed. See TCPInterface::HasNewIncomingConnection() loggerPlugin.SetServerParameters(serverAddress, "functionLog.sqlite"); ``` -------------------------------- ### Installation Rules for Non-Windows/Unix Source: https://github.com/slikesoft/slikenet/blob/master/Lib/DLL/CMakeLists.txt Defines installation rules for SLikeNetDLL and its associated configuration files and headers on non-Windows and Unix-like systems. This makes the library available for use by other projects. ```cmake IF(NOT WIN32 OR UNIX) configure_file(../../slikenet-config-version.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/slikenet-config-version.cmake @ONLY) install(TARGETS SLikeNetDLL EXPORT SLikeNetDLL DESTINATION lib/slikenet-${SLikeNet_VERSION}) INSTALL(FILES ${ALL_COMPATIBILITY_HEADER_SRC} DESTINATION include/slikenet-${SLikeNet_VERSION}) INSTALL(FILES ${ALL_COMPATIBILITY_HEADER_SRC_2} DESTINATION include/slikenet-${SLikeNet_VERSION}/slikenet/slikenet) INSTALL(FILES ${ALL_HEADER_SRCS} DESTINATION include/slikenet-${SLikeNet_VERSION}/slikenet/include/slikenet) INSTALL(FILES ../../slikenet-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/slikenet-config-version.cmake DESTINATION lib/slikenet-${SLikeNet_VERSION}) INSTALL(EXPORT SLikeNetDLL DESTINATION lib/slikenet-${SLikeNet_VERSION}) ENDIF(NOT WIN32 OR UNIX) ``` -------------------------------- ### Initialize and Start RakNet Peer Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/detailedimplementation.html Initializes the RakNet peer object with specified parameters and starts the network connection. Sets the maximum number of allowed connections and the port for receiving data. ```C++ RakNet::SocketDescriptor sd(serverPort,0); peer->Startup(maxConnectionsAllowed, &sd, 1); peer->SetMaximumIncomingConnections(4); ``` -------------------------------- ### Start Fully Connected Mesh with Password Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/fullyconnectedmesh.html Initializes the Fully Connected Mesh plugin with a specified password to control network access. This method should be called before the plugin starts processing connections. ```C++ /// Set the password to use to connect to the other systems void Startup(const char *password, int _passwordLength); ``` -------------------------------- ### Connect as a Client Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/detailedimplementation.html Initiates network threads and attempts to connect to a specified server. Startup configures the network, and Connect establishes the connection. Connection attempts are asynchronous. ```C++ peer->Startup(1, &SocketDescriptor(), 1); peer->Connect(serverIP, serverPort, 0, 0); ``` -------------------------------- ### Basic CMake Configuration Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/IrrlichtDemo/CMakeLists.txt Sets the minimum CMake version and gets the current folder name. This is a standard starting point for CMake projects. ```cmake cmake_minimum_required(VERSION 2.6) GETCURRENTFOLDER() ``` -------------------------------- ### Client-Side Cloud Client Setup Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/cloudcomputing.html Initialize CloudClient on the client and optionally provide custom allocators and callbacks for handling downloaded data. ```C++ CloudClient cloudClient; rakPeer->AttachPlugin(&cloudClient); // Optional: Provide an overridden allocator to store or deallocate the downloaded rows in your own application Cloud_Allocator cloudAllocator; // Optional: You'll want to actually provide an overridden instance to handle downloads Cloud_ClientCallback clientCallback; // Set the allocation callbacks cloudClient.SetCallbacks(&cloudAllocator, &clientCallback); ``` -------------------------------- ### Establishing Routing with Router2 Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/router.html Use this code to establish a route to a destination system when using the Router2 plugin. It parses a message to get the destination GUID, source-to-destination port, and then calls EstablishRouting. ```C++ RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); RakNetGUID endpointGuid; bs.Read(endpointGuid); unsigned short sourceToDestPort; bs.Read(sourceToDestPort); char ipAddressString[32]; packet->systemAddress.ToString(false, ipAddressString); rakPeerInterface->EstablishRouting(ipAddressString, sourceToDestPort, 0,0); ``` -------------------------------- ### C# Project Setup - Windows Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/swigtutorial.html Steps to set up a C# project in Visual Studio to use RakNet SWIG bindings. This includes adding generated files and configuring build platforms. ```csharp using RakNet; ``` -------------------------------- ### Example of a Successive Approximation Script for Progressive JPEG Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jpeg-7/wizard.txt This script generates a progressive JPEG file using successive approximation, equivalent to the default script for YCbCr images. It includes multiple stages for sending different bits of the coefficients, starting with the least significant bits. ```text # Initial DC scan for Y,Cb,Cr (lowest bit not sent) 0,1,2: 0-0, 0, 1 ; # First AC scan: send first 5 Y AC coefficients, minus 2 lowest bits: 0: 1-5, 0, 2 ; # Send all Cr,Cb AC coefficients, minus lowest bit: # (chroma data is usually too small to be worth subdividing further; # but note we send Cr first since eye is least sensitive to Cb) 2: 1-63, 0, 1 ; 1: 1-63, 0, 1 ; # Send remaining Y AC coefficients, minus 2 lowest bits: 0: 6-63, 0, 2 ; # Send next-to-lowest bit of all Y AC coefficients: 0: 1-63, 2, 1 ; # At this point we've sent all but the lowest bit of all coefficients. # Send lowest bit of DC coefficients 0,1,2: 0-0, 1, 0 ; # Send lowest bit of AC coefficients 2: 1-63, 1, 0 ; 1: 1-63, 1, 0 ; # Y AC lowest bit scan is last; it's usually the largest scan 0: 1-63, 1, 0 ; ``` -------------------------------- ### UDT Slow Start Phase Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/congestioncontrol.html If in the slow start phase, the sending rate (SND) is set to 1/AS. Slow start then ends. ```pseudocode If it is in the slow start phase, set SND to 1/AS. Slow start ends. Stop. ``` -------------------------------- ### Console Server Initialization and Update Loop Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/consoleserver.html This snippet shows the basic setup for a console server, including adding command parsers and setting the transport provider. It demonstrates the main update loop where commands are processed and logs are written. ```C++ ConsoleServer consoleServer; TelnetTransport tt; RakNetCommandParser rcp; LogCommandParser lcp; consoleServer.AddCommandParser(&rcp); consoleServer.AddCommandParser(&lcp); consoleServer.SetTransportProvider(ti, port); lcp.AddChannel("TestChannel"); while (1) { lcp.WriteLog("TestChannel", "Test of logger"); consoleServer.Update(); // Game loop here } ``` -------------------------------- ### Client: Create NatPunchthroughClient Instance Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/natpunchthrough.html Instantiate the NatPunchthroughClient plugin. ```C++ NatPunchthroughClient natPunchthroughClient; ``` -------------------------------- ### Server: Create NatPunchthroughServer Instance Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/natpunchthrough.html Instantiate the NatPunchthroughServer plugin on your server. ```C++ NatPunchthroughServer natPunchthroughServer; ``` -------------------------------- ### Install gdb (Debian/Ubuntu) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Command to install the GDB debugger on Debian-based systems like Ubuntu. ```bash sudo apt-get install gdb ``` -------------------------------- ### Install g++ (Debian/Ubuntu) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Command to install the g++ compiler on Debian-based systems like Ubuntu. ```bash sudo apt-get install gcc-c++ sudo apt-get install build-essential ``` -------------------------------- ### Start as a Server Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/detailedimplementation.html Initializes RakNet to operate as a server, specifying the maximum number of allowed client connections and the port to listen on. SetMaximumIncomingConnections further refines the connection limit. ```C++ peer->Startup(maxConnectionsAllowed, &SocketDescriptor(serverPort,0), 1); peer->SetMaximumIncomingConnections(maxPlayersPerServer); ``` -------------------------------- ### Rackspace API Setup and Authentication Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/rackspaceinterface.html Initializes the TCPInterface and Rackspace classes, authenticates with Rackspace, and sets up a loop to process network events. ```cpp #include "Rackspace.h" #include "TCPInterface.h" RakNet::Rackspace rackspaceApi; RakNet::TCPInterface tcpInterface; RakNet::RackspaceEventCallback_Default callback; tcpInterface.Start(0, 0, 1); rackspaceAPI.Authenticate(&tcpInterface, "myAuthURL", "myRackspaceUsername", "myRackspaceAPIKey"); while (1) { for (RakNet::Packet *packet=tcpInterface.Receive(); packet; tcpInterface.DeallocatePacket(packet), packet=tcpInterface.Receive()) rackspaceApi.OnReceive(packet); rackspaceApi.OnClosedConnection(tcpInterface.HasLostConnection()); } ``` -------------------------------- ### Install g++ (Yum) Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/README.md Command to install the g++ compiler on systems using yum package manager. ```bash yum install gcc-c++ ``` -------------------------------- ### Configure, Compile, and Install Jansson Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jansson-2.4/README.rst Standard autotools commands to build and install Jansson from a source tarball. ```bash $ ./configure $ make $ make install ``` -------------------------------- ### Registering a Command with ConsoleServer Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/consoleserver.html This example demonstrates how to register a new command with the ConsoleServer. It shows the use of RegisterCommand to define the command's name, parameter count, and help string. ```C++ RegisterCommand(4, "Startup","( unsigned short maxConnections, int _threadSleepTimer, unsigned short localPort, const char *forceHostAddress );"); ``` -------------------------------- ### Get JSON Value Type Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jansson-2.4/doc/apiref.rst Use json_typeof() to get the type of a JSON value. This function is implemented as a macro for performance. ```c int json_typeof(const json_t *json); ``` -------------------------------- ### Initiating Directory Download on Client Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/directorydeltatransfer.html Client-side call to initiate a directory download. Specify source, destination, transfer options, server address, and a callback for progress. ```c++ directoryDeltaTransfer.DownloadFromSubdirectory("skins", "downloaded\skins", true, serverAddress, &transferCallback, HIGH_PRIORITY, 0); ``` -------------------------------- ### Setting up Directory Delta Transfer Plugin Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/directorydeltatransfer.html Steps to initialize and configure the DirectoryDeltaTransfer plugin for server-side use. Ensure FileListTransfer is attached and connected. ```c++ directoryDeltaTransfer.SetFileListTransferPlugin(&fileListTransfer); directoryDeltaTransfer.SetApplicationDirectory("c:\myGame"); directoryDeltaTransfer.AddUploadsFromSubdirectory("skins"); ``` -------------------------------- ### Get Bzip2 File Error Information Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/bzip2-1.0.6/manual.html Call BZ2_bzerror to get a string describing the last error for a BZFILE and its numerical error code. ```C const char * BZ2_bzerror ( BZFILE *b, int *errnum ); ``` -------------------------------- ### QueryConstruction Example for Peer-to-Peer Games Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/replicamanager3.html Illustrates QueryConstruction for peer-to-peer games, managing object ownership and construction states based on component configurations and host system status. ```C++ if (destinationConnection->HasLoadedLevel() == false) return RM3CS_NO_ACTION; if (IsAStaticObject()) { if(fullyConnectedMesh2->IsHostSystem()) return RM3CS_ALREADY_EXISTS_REMOTELY; else return RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT; } else { Replica3P2PMode p2pMode = R3P2PM_SINGLE_OWNER; for (int i=0; i < components.Size(); i++) { p2pMode = components[i]->QueryP2PMode(); if(p2pMode != R3P2PM_SINGLE_OWNER) break; } return QueryConstruction_PeerToPeer(destinationconnection, p2pMode); } ``` -------------------------------- ### Process Verified Join Start and Open NAT Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/nattraversalarchitecture.html Handles the start of a verified join process. It retrieves the list of participants and initiates NAT punchthrough for each. ```C++ case ID_FCM2_VERIFIED_JOIN_START: { DataStructures::List addresses; DataStructures::List guids; fullyConnectedMesh2->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids); for (unsigned int i=0; i < guids.Size(); i++) natPunchthroughClient->OpenNAT(guids[i], game->natPunchServerAddress); } break; ``` -------------------------------- ### PHP Directory Server Upload and Download Example Source: https://github.com/slikesoft/slikenet/blob/master/readme.txt Combines upload and download functionality in a single request. Uploaded data is skipped for the download part of the same request. ```php DirectoryServer.php?query=upDown&downloadPassword=xxx&uploadPassword=yyy ``` -------------------------------- ### PHP Directory Server Upload Example Source: https://github.com/slikesoft/slikenet/blob/master/readme.txt Demonstrates how to upload game server data to the Directory Server. The body contains column names and values, separated by ASCII 1. System address and update time are automatically added. ```php DirectoryServer.php?query=upload&uploadPassword=yyy __GAME_PORT?1235?__GAME_NAME?My game?MapType?Deathmatch?Number of players?5 ``` -------------------------------- ### PHP Directory Server Download Example Source: https://github.com/slikesoft/slikenet/blob/master/readme.txt Retrieves all stored rows that are less than 60 seconds old. Output format is similar to upload, with rows separated by ASCII 2. ```php DirectoryServer.php?query=download&downloadPassword=xxx ``` -------------------------------- ### Custom Malloc Implementation Example Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/custommemorymanagement.html An example of how to implement a custom memory allocation function that can be assigned to the rakMalloc pointer. This function wraps the standard C malloc. ```cpp #include "RakMemoryOverride.h" void *MyMalloc(size_t size) { return malloc(size); } ``` -------------------------------- ### Minimal SQLiteServerLoggerPlugin TCP Setup Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/sqlite3loggerplugin.html Provides a basic configuration for the SQLiteServerLoggerPlugin using PacketizedTCP. This setup enables session management for automatic log file creation. ```C++ PacketizedTCP packetizedTCP; RakNet::SQLiteServerLoggerPlugin loggerPlugin; loggerPlugin.SetSessionManagementMode(RakNet::SQLiteServerLoggerPlugin::CREATE_SHARED_NAMED_DB_HANDLE, true, ""); packetizedTCP.AttachPlugin(&loggerPlugin); packetizedTCP.Start(38123,8); ``` -------------------------------- ### Server-Side Cloud Server Setup Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/cloudcomputing.html Configure CloudServer on the server to manage client uploads and downloads. Optionally restrict data transfer sizes per client. ```C++ CloudServer cloudServer; rakPeer->AttachPlugin(&cloudServer); // Restrict how many bytes a client can upload to this server. cloudServer.SetMaxUploadBytesPerClient(MAX_UPLOAD_BYTES); cloudServer.SetMaxBytesPerDownload(MAX_DOWNLOAD_BYTES); ``` -------------------------------- ### Creating a Server XML Request Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/rackspaceinterface.html Constructs an XML string for creating a new server instance on Rackspace, specifying name, image, and flavor IDs. ```C++ RakNet::RakString xml("" " ", name.C_String(), imageId.C_String(), flavorId.C_String()); AddOperation(RO_CREATE_SERVER, "POST", "servers", xml); ``` -------------------------------- ### QuerySerialization Example for Component-Based Systems Source: https://github.com/slikesoft/slikenet/blob/master/Help/RakNet/documentation/replicamanager3.html Demonstrates how to implement QuerySerialization in a component-based system. It handles serialization of static objects by the host and allows components to override serialization behavior. ```C++ if (IsAStaticObject()) { // Objects loaded with the level are serialized by the host if (fullyConnectedMesh2->IsHostSystem()) return RM3QSR_CALL_SERIALIZE; else return RM3QSR_DO_NOT_CALL_SERIALIZE; } else { // Allow components opportunity to overwrite method of serialization for (int i=0; i < components.Size(); i++) { RM3QuerySerializationResult res = components[i]->QuerySerialization(destinationconnection); if(res != RM3QSR_MAX) return res; } return QuerySerialization_PeerToPeer(destinationconnection); } ``` -------------------------------- ### JSON String with Null Character Example Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/jansson-2.4/doc/conformance.rst This example demonstrates a JSON string that, if decoded by Jansson, would result in a parse error due to the presence of an embedded null character. ```json ["this string contains the null character: \u0000"] ``` -------------------------------- ### PortAudio Initialization Source: https://github.com/slikesoft/slikenet/blob/master/DependentExtensions/portaudio_v18_1/docs/pa_drivermodel.c.txt Initializes the PortAudio library by discovering and initializing all available driver models. Returns an error if already initialized or if memory is insufficient. ```c PaError Pa_Initialize( void ) { PaError result = paNoError; int i, initializerCount; PaDriverModelImplementation *impl; if( driverModels != 0 ) return paAlreadyInitialized; /* count the number of driverModels */ initializerCount=0; while( driverModelInitializers[initializerCount] != 0 ){ ++initializerCount; } driverModels = malloc( sizeof(PaDriverModelImplementation*) * initializerCount ); if( driverModels == NULL ) return paInsufficientMemory; numDriverModels = 0; for( i=0; i #include #include int main() { // Declare RakPeerInterface RakNet::RakPeerInterface *rakPeer; // Declare variables char serverOrClient; unsigned short port; char ipAddress[64]; // Prompt user to choose between server and client std::cout << "Enter 'c' to run as client, 's' to run as server: "; std::cin >> serverOrClient; serverOrClient = std::tolower(serverOrClient); // Initialize RakPeerInterface rakPeer = RakNet::RakPeer::GetInstance(); // Set up parameters based on user choice RakNet::SocketDescriptor socketDescriptor; if (serverOrClient == 's') { // Server setup port = 5000; // Default server port socketDescriptor.port = port; // Startup parameters for server // Maximum incoming connections: 32 // Server port: port // IP address: RakNet::UNASSIGNED_ADDRESS (listen on all interfaces) // threadSleepTimer: 30 milliseconds // maxConnections: 32 // // For more details on parameters, see the RakPeerInterface documentation. // // RakNet::Startup(unsigned int maxConnections, unsigned short port, RakNet::SystemAddress systemAddress=RakNet::UNASSIGNED_ADDRESS, int threadSleepTimer=30, int customThreadPriority=NORMAL_PRIORITY_HIGH) rakPeer->Startup(32, port, 0, 30); rakPeer->SetMaximumIncomingConnections(32); } else { // Client setup std::cout << "Enter server IP address: "; std::cin >> ipAddress; port = 5000; // Default server port // Startup parameters for client // Maximum incoming connections: 1 (only need to connect to one server) // Server port: 0 (automatically choose a port) // IP address: RakNet::UNASSIGNED_ADDRESS (not used for client startup) // threadSleepTimer: 30 milliseconds // maxConnections: 1 // // For more details on parameters, see the RakPeerInterface documentation. // // RakNet::Startup(unsigned int maxConnections, unsigned short port, RakNet::SystemAddress systemAddress=RakNet::UNASSIGNED_ADDRESS, int threadSleepTimer=30, int customThreadPriority=NORMAL_PRIORITY_HIGH) rakPeer->Startup(1, 0, 0, 30); // Connect to the server // IP address: ipAddress // Port: port // password: nullptr (no password) // passwordLength: 0 // connectionTimeout: 3000 milliseconds // // For more details on parameters, see the RakPeerInterface documentation. // // RakNet::Connect(const char *host, unsigned short port, const char *password=0, int passwordLength=0, RakNet::SystemAddress systemAddress=RakNet::UNASSIGNED_ADDRESS, int connectionTimeout=3000, int retryFrequency=100, int retryTimes=7) rakPeer->Connect(ipAddress, port, nullptr, 0, RakNet::UNASSIGNED_ADDRESS, 3000, 100, 7); } // Main loop for receiving messages (simplified for this example) // In a real application, you would process incoming packets here. // For now, we'll just wait for a short period. RakNet::TimeMS endTime = RakNet::GetTimeMS() + 5000; // Wait for 5 seconds while (RakNet::GetTimeMS() < endTime) { RakNet::Packet *packet = rakPeer->Receive(); if (packet) { // Process packet here if needed rakPeer->DeallocatePacket(packet); } RakNet::RakSleep(30); } // Destroy RakPeerInterface RakNet::RakPeer::DestroyInstance(rakPeer); return 0; } ```