Tag Archives: Tutorial

Tutorial : RakNet Replica3 on the iPhone

Sorry this took a while getting out, it took a bit longer than expected to finish.

One of the more useful features of RakNet, particularly for games, is the ReplicaManager plugin. This piece of code handles “replication” of objects, ensuring that all clients have the same state as the server. For example, in some of my previous posts I demonstrated the feature by running a physics simulation on a server and viewing the scene on several connecting clients. Replica is very scaleable and allows for fine-grained control over what aspects of an object are transmitted over the network, how reliable the arrival order is, etc. This tutorial will only cover a basic client-side iPhone integration based on the Replica sample provided with RakNet; more details on the specifics of using the system can be found in the RakNet forums and documentation section.

I’m going to assume that you’ve looked at the previous tutorials using RakNet, and have at least compiled an iOS RakNet library. We’ll need to use that to compile the application in this tutorial.

The first step is to create a new “View-based Application” project for the iPhone. You can name it whatever you want, but I’m using RaknetReplicaSample and this name may appear in some screenshots.

The original RakNet sample was contained in a single .cpp file that would run both  a client server, making things a bit confusing to work with. I’ve split the example into several files and added a logger class that will print to a UITextView, which makes things a bit easier on the iOS platform. These files, along with a compiled version of the RakNet sample for OS X, can be downloaded here.

Import these files into your newly created Xcode project and add them to the Classes folder. There are still some hooks to add to the ViewController and AppDelegate files. These are similar to the ones made for the previous tutorial on setting up a RakNet chat client on the iPhone, but there are a few key differences in the ViewController.

We’ll start off with the AppDelegate though. Like last time, we need to setup an NSTimer to run our network loop. Add a new NSTimer to the AppDelegate.h file at the end of the @interface declaration:

NSTimer * mTimer;

And a new method to actually call the network update function:

-(void) networkUpdate: (NSTimer *) pTimer;

The interface should look something like this:

In the corresponding implementation file, <ProjectName>AppDelegate.m, add the following line at the end of the application:didFinishLaunching: method:

mTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(networkUpdate:) userInfo:nil repeats: YES];

Then, add an implementation for the networkUpdate method:

-(void) networkUpdate: (NSTimer *) pTimer
{
	[self.viewController tickClient];
}

That’s all that needs to be done in AppDelegate. In theViewController.h, add the following includes to the top of the file, directly after UIKit.h. Please keep them in this order as well:

#include "SampleReplica.h"
#include "SampleConnection.h"
#include "SampleReplicaManager.h"
#include "Logger.h"

Then add the following items to the @interface declaration:

	NetworkIDManager networkIdManager;
	RakPeerInterface *rakPeer;
	ReplicaManager3Sample replicaManager;
	SocketDescriptor sd;
	Packet *packet;

	UITextView* mTextView;

This is similar to the chat tutorial, but now we had a new “ReplicaManager” instance. This class and its super class handle much of the work behind the object replication process.

We’ll also need to add the following lines after the closing brace on the @interface declaration:

-(void)tickClient;

@property (nonatomic,retain) IBOutlet UITextView* mTextView;

In the implementation file for the ViewController, we first need to @synthesize  the UITextView by adding the following line after the @implementation declaration:

@synthesize mTextView;

In the viewDidLoad method, add the following block of code after the call to the super class:

	Logger::getLogger()->setTextView(mTextView);

	sd.socketFamily=AF_INET;
	sd.port=0;

	rakPeer = RakNet::RakPeerInterface::GetInstance();
	rakPeer->Startup(32,&sd,1);
	rakPeer->AttachPlugin(&replicaManager);
	replicaManager.SetNetworkIDManager(&networkIdManager);
	rakPeer->SetMaximumIncomingConnections(32);	

	rakPeer->Connect("192.168.2.17",12345,0,0,0);

Just like the chat client example, the IP address can and should be changed to suit the environment you’re using. The port needs to remain as it is, since the RakNetReplicaSample server is hardcoded to use this port. The port shouldn’t be a problem for anyone.

Next, add the tickClient method. This method is called by our NSTimer once every 10th of a second and updates the network:

-(void)tickClient
{
	for (packet = rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet = rakPeer->Receive())
	{
		switch (packet->data[0])
		{
			case ID_CONNECTION_ATTEMPT_FAILED:
				Logger::getLogger()->appendLine(@"Connection failed\n");
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				Logger::getLogger()->appendLine(@"Connection failed - No free incoming connections\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				Logger::getLogger()->appendLine(@"Connection request accepeted\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				Logger::getLogger()->appendLine(@"Disconnecting\n");
				break;
			case ID_CONNECTION_LOST:
				Logger::getLogger()->appendLine(@"Connection lost\n");
				break;
			case ID_SND_RECEIPT_LOSS:
			case ID_SND_RECEIPT_ACKED:
			{
				uint32_t msgNumber;
				memcpy(&msgNumber, packet->data+1, 4);

				DataStructures::Multilist replicaListOut;
				replicaManager.GetReplicasCreatedByMe(replicaListOut);
				DataStructures::DefaultIndexType idx;
				for (idx=0; idx < replicaListOut.GetSize(); idx++) 
				{ 					
                                      ((SampleReplica*)replicaListOut[idx])->NotifyReplicaOfMessageDeliveryStatus(packet->guid,msgNumber, packet->data[0]==ID_SND_RECEIPT_ACKED);
				}
			}
				break;
		}
	}
}

Finally, add two lines of clean-up to the viewDidUnload method to disconnect from the network:

	rakPeer->Shutdown(100,0);
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);

Like last time, we also need to tell the compiler that this project will contain some C++ code. This means that all the .m files need to be renamed to .mm, or set to compile as Objective-C++ by right clicking them, going to Get Info, and changing the File Type field to Objective-C++:

That should cover all of the code changes needed. You’ll also need to add a new UITextView to the interface builder and link it to the UITextView created in the ViewController class. This will be used to display output from the server and any connect/disconnect messages.

Like last time, you’ll need to include your RakNet library and add the RakNet source directory to your header search path. At this point, everything should be ready to compile.

To test the app, first start the provided OS X Replica application. Since this application is taken straight from RakNet, it can run as a client, server or peer-to-peer instance. Start it as a server by entering ‘s’ into the console. You can create new objects by pressing ‘c’, and assign them random values with ‘r’. Delete all created objects with the ‘d’ key. All three of these actions will be replicated on the client, and can be verified by checking the output UITextView on the iPhone app.

As always, I’m happy to help sort out any issues that come up with the tutorial. Let me know in the comments if you need anything, or if there are any other specific RakNet samples that you want to see ported to the iPhone.

T

Advertisements

Tutorial : RakNet Chat on the iPhone

The purpose of this tutorial is to set up a basic chat client on the iPhone that is able to connect to a chat server running on your computer. Since this tutorial is for the iPhone, I’m going to assume that you’re using a Mac and therefore the example chat server is intended to be run on OS X. We’ll get to that in a minute though.

I’m going to assume you’ve completed the last RakNet tutorial and have compiled RakNet into an iPhone library. We’ll be using that library again here in this tutorial.

The first step is to create a fresh iPhone project. I chose a View-based Application since it’s basic and doesn’t include anything extra:

You can name the project whatever you want, but I’ll be using “RaknetTextClient.”

Once the project is created, the first thing you’ll need to do is add the library to the project as described in the last tutorial. I’ll paraphrase it again here though:

  • To add the library, right-click the Frameworks folder and go to Add>Existing items. Chose your RakNet library.
  • To add the headers, right-click the project and go to Get Info. Scroll down to the Search Paths and add the folder containing your RakNet source to the Header Search Paths variable.

With these items done you’re ready to start adding RakNet code. First, open up AppDelegate.h. We’re going to use this file to control the network updates for RakNet. To do this, we need to add a new NSTimer to the interface and a networkUpdate method. After these changes, I have this:

If you want to copy the code, here are the changes:

NSTimer * mTimer;
-(void) networkUpdate: (NSTimer *) theTimer ;

Since our project is using RakNet, it will need to be able to compile C++ code. To do this, we need to rename our AppDelegate.m file to AppDelegate.mm. This will tell Xcode that it can expect some C++ code in the project.

In the newly renamed file, we also need to make some changes to work with the changes to AppDelegate.h. The first item of business is to add the following line to the method -(BOOL)application: … didFinishLaunchingWithOptions: …

mTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(networkUpdate:) userInfo:nil repeats: YES];

This line can go anywhere, but I placed it right before the return YES; line. The next step is to add the networkUpdate method. This can go anywhere in the file, but I put it directly after the method mentioned above. The method looks like:

-(void) networkUpdate: (NSTimer *) theTimer
{
[self.viewController tickClient];
}

That’s all for AppDelegate changes, onto the ViewController modifications. These are a bit more extensive since we’re going to be adding some actual RakNet code. The first set of changes needed are in ViewController.h. Add the following #includes below the existing #includes in the file:

#include "MessageIdentifiers.h"
#include "RakPeerInterface.h"
#include "RakNetStatistics.h"
#include "RakNetTypes.h"
#include "BitStream.h"
#include "PacketLogger.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include "RakNetTypes.h"
#include "Kbhit.h"
#include <unistd.h>
#include "Gets.h"

After all of the #includes you’ll also need to add  using namespace RakNet; before the @interface declaration. Inside the declaration, add the following variables:

RakPeerInterface *mRakPeer;
SystemAddress mClientID;
Packet* mPacket;
unsigned char mPacketID;
UITextField *mSendText;
UITextView *mTextBox;

The first four are for RakNet, and the last two are for the simple UI we’re going to set up in a bit. We also need to add some methods and properties; these are added after the interface declaration. Add the following:

-(void)appendMessage:(NSString*)message;
-(IBAction)sendMessage;
-(void)tickClient;

@property (nonatomic, retain) IBOutlet UITextField *mSendText;
@property (nonatomic, retain) IBOutlet UITextView *mTextBox;

That’s all for the ViewController header file.

Like the AppDelegate.mm file, we need to rename the ViewController.m file so it has the .mm extension. Inside the file, we first need to add a @synthesize line for our two properties. This goes directly after the @implementation line.

@synthesize mTextBox, mSendText;

Directly after this, I added the following method that was taken straight from RakNet’s chat sample:

unsigned char GetPacketIdentifier(RakNet::Packet *p)
{
	if (p==0)
		return 255;

	if ((unsigned char)p->data[0] == ID_TIMESTAMP)
	{
		RakAssert(p->length > sizeof(RakNet::MessageID) + sizeof(RakNet::Time));
		return (unsigned char) p->data[sizeof(RakNet::MessageID) + sizeof(RakNet::Time)];
	}
	else
		return (unsigned char) p->data[0];
}

This method will be used by the network code to determine what sort of message is being sent. The next code change is in the viewDidLoad method. By default this method is commented out, so uncomment it and then add the following code after [super viewDidLoad]; 

mRakPeer  = RakPeerInterface::GetInstance();
mClientID = UNASSIGNED_SYSTEM_ADDRESS;

SocketDescriptor socketDescriptor(54001,0);
socketDescriptor.socketFamily=AF_INET;

mRakPeer->Startup(8,&socketDescriptor, 1);
mRakPeer->SetOccasionalPing(true);	

ConnectionAttemptResult car = mRakPeer->Connect("192.168.2.17", 54000, "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"));

RakAssert(car==RakNet::CONNECTION_ATTEMPT_STARTED);

You’ll want to change a few things here based on your network configuration. In the Connect() method, the first number is the IP address of the machine that will be running the server and the second number is the port for the server. If you’re only going to run this application on the iPhone simulator, you can use “127.0.0.1” as the IP. If you plan on testing on the device itself you’ll need to use the internal IP of the computer that you plan to use as the server. There are a variety of ways to find this; I got mine by checking the config page for my router. If you’re using AirPort and a WiFi connection it’ll be list on the first page of the AirPort settings, something like “AirPort is connected toand has the IP address 192.168.2.17.” You should be able to keep the port number the same. The “Rumpelstiltskin” is the default password in RakNet and should be left as-is to work with the server application.

Anyways, there are a few more changes that need to be made. Add the following set of methods (it’s a long one):

//Sends a message to the server and appends it to the text view
- (IBAction)sendMessage
{
	NSString* message = [NSString stringWithFormat:@"iPhone: %@",mSendText.text];
	const char* cMessage = [message cStringUsingEncoding:NSASCIIStringEncoding];
	mRakPeer->Send(cMessage, (int) strlen(cMessage)+1, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);

	[mSendText setText:@""];
	[self appendMessage:message];
}

//Appends a string to the text view
-(void)appendMessage:(NSString*)message
{
	mTextBox.text = [NSString stringWithFormat:@"%@\n%@", mTextBox.text,message];
}

//Update the network and checks for incoming packets
-(void)tickClient
{
	for (mPacket = mRakPeer->Receive(); mPacket; mRakPeer->DeallocatePacket(mPacket), mPacket=mRakPeer->Receive())
	{
		// We got a packet, get the identifier with our handy function
		mPacketID = GetPacketIdentifier(mPacket);

		// Check if this is a network message packet
		switch (mPacketID)
		{
			case ID_DISCONNECTION_NOTIFICATION:
				// Connection lost normally
				[self appendMessage:@"Disconnected from server."];
				break;
			case ID_ALREADY_CONNECTED:
				[self appendMessage:@"Already connected to server."];
				break;
			case ID_INCOMPATIBLE_PROTOCOL_VERSION:
				[self appendMessage:@"Protocol version error"];
				break;
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				[self appendMessage:@"A client disconnected from the server."];
				break;
			case ID_REMOTE_CONNECTION_LOST: 
				[self appendMessage:@"A client lost connection with the server."];
				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION: 
				[self appendMessage:@"Another client is connecting!"];
				break;
			case ID_CONNECTION_BANNED:
				[self appendMessage:@"You are banned from this server."];
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				[self appendMessage:@"Connection failed. "];
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				[self appendMessage:@"Server is full."];
				break;

			case ID_INVALID_PASSWORD:
				[self appendMessage:@"Invalid password."];
				break;

			case ID_CONNECTION_LOST:
				[self appendMessage:@"Connection lost."];
				break;

			case ID_CONNECTION_REQUEST_ACCEPTED:
				[self appendMessage:@"Connection accepted."];
				break;
			default:
				[self appendMessage:[NSString stringWithCString:(const char*)mPacket->data encoding:NSASCIIStringEncoding]];
				break;
		}
	}
}

There’s only one more change needed to this file and then we’ll build the UI. In the viewDidUnload method, add the following code to cleanup the network:

// Be nice and let the server know we quit.
mRakPeer->Shutdown(300);

// We're done with the network
RakPeerInterface::DestroyInstance(mRakPeer);

That’s all the source code changes we’ll need! Next, open up theViewController.xib file. We need to place 3 items: a UITextView, a UITextField and a UIButton. The UITextView should be connected to the “mTextBox” variable, and then UITextField should connect to the “mSendText” variable. The “sendMessage” method should be connect to the UIButton’s Touch Up event. Here’s the full configuration I used:

Save the .xib, and then compile. At this point you’re ready to test the app, so you’ll need to run some sort of server. I’ve compiled the RakNet sample server as a Mac app, which will work with this iPhone app. You can download the server file here.

Download and launch the server app, and enter “54000” as the port to listen on. You can then run your iPhone app on the simulator or device, and it should connect to the server. A connection message will be displayed in the server window when a client successfully connects. Typing messages in the server window will send the messages to all connected clients, as well typing/sending messages on the iPhone app.

Let me know if there are any issues and I’ll try to help resolve them. I’m going to do put up an example of using RakNet’s ReplicaManager on the iPhone as well, possibly tonight but more likely tomorrow.

T


Tutorial : RakNet for the iPhone

A few people have shown interest in running RakNet on the iPhone, and the term appears at least once a day on my “Search Engine Terms” stats column. I initially planned on just putting up a package containing an Xcode project and a few of the RakNet samples, but I’m not sure how this would work with the license agreement. To be safe, I’ve written a general tutorial here instead of posting any of the RakNet source.

One of the common ways to include an external package on Mac is to use a Framework, however this option is not available for the iPhone. This means that there are only really two ways to get RakNet into an iPhone application: compile it directly as part of the project, or link it as an external library.

The first option is definitely the easiest to set up; all you need to do is copy the RakNet files into your project’s source code directory and then include them in the Xcode project as you would any file. This is the route I initially took in my own integration, but I’ve since switched to using a library. I’m not going to cover this method here as it’s pretty straight forward to use, but if you want to use it and have trouble I’m happy to help.

The second option, the library, generally requires that you setup a second Xcode project specifically for building the RakNet library. It also requires that you compile separate versions for the iPhone Simulator and iPhone Device, since they have different CPU architectures. A helpful comment from Paul Solt on an earlier post showed how these two versions can be compiled into a single library; I’ll cover that here as well.

So, onto the tutorial.

The first step is to open up Xcode and create a new project. From the iOS sub group, you’ll want to select “Library”, and then “Cocoa Touch Static Library”, like so:

Go ahead and create the project. I called my “Test” in the screenshots here, but you’ll probably want to go with something along the lines of “RakNetLibrary.”

The next step is to input the source from RakNet into your new project. Right click the “Classes” folder and go to Add > Existing Files…

In the menu that comes up, navigate to the folder containing the RakNet source code. This doesn’t have to be in your project directory, since we’ll tell Xcode to copy the files over. Select all of the files, but don’t include the “cat” folder. This isn’t needed for most RakNet use cases, and does not compile on OS X as of yet.

After selecting the files and clicking “Add”, make sure the window that comes up has the following settings:

Once everything is set, click Add.

At this point, you’re ready to compile. Go to the “Build” item on the toolbar and select “Build” from it, or hit command-B. There are a hundred or so warnings that show up, but these aren’t serious and are just from missing #directives and a macro redefinition. It’s possible they’ve been fixed in builds of RakNet after this tutorial was posted.

A commenter, Richard, has pointed out that with the newer versions of Xcode there’s a problem with one of the compiler settings. The problem occurred for him with Xcode 4.2, but if you have trouble with any version of Xcode 4.0+ you might want to check into this. Richard says:

The problem turned out the be the compiler, for previous versions of the SDK the default compiler is “LLVM GCC 4.2” however for the new SDK I guess the default compiler is “Apple LLVM Compiler 3.0”. For whatever reason Apple LLVM Compiler 3.0, cause the errors and many extra warnings.

You’ll want to set your compiler version to GCC 4.2, which is located in the Project settings. To do this, right click the project, select Get Info and scroll down to the section labeled Compiler Version.

After the build is finished a file named “lib.a” will be created. This file is by default in the build/Debug-iphonesimulator/ folder by default, but will depend on what settings you used to build the project.

At this point the library is useable, however you’ll most likely wanted to compile a Device version as well. The device and simulator versions can be combined into a single universal binary using lipo, a tool included on the Mac. Assuming your device library is _d and your simulator library is _s, you can create a universal binary by running the following in Terminal:

lipo -create libTest_d.a libTest_s.a -output libTest_u.a

At this point, the library will be useable for any iOS development you do, whether it be on the simulator or device.

To include the library in an iPhone project, I generally add it to the “Frameworks” folder along with the other Cocoa frameworks. Right click that folder and select Add>Existing Items in the same fashion that you did for the RakNet source files. Since the file is only a library and does not contain any header information, you’ll also need to add references to the RakNet header files. This can be done by adding the RakNet source folder to the header search paths. Right click on the project, and select Get Info. From there, scroll down to the “Search Paths” section and double click the Header Search Paths entry:

Add the folder that contains your RakNet source code to the list, which is most likely empty on a new project. This should be all you need to get going with RakNet!

Since this post has become rather long, I’m going to do a second one tomorrow with some examples of how to actually use RakNet to set up a simple chat client app for the iPhone that can communicate with the RakNet Chat Server example.

T


%d bloggers like this: