Networking tutorial
From Spheriki
Ever thought of creating a multiplayer game? Via the internet, maybe? This is how.
Concepts
You have 2 different scripts... one person has a client, and the other has a server script.
Server example
First, we make the server script.
var font = GetSystemFont(); var port = 1234; var data = ListenOnPort(port);
So now data is a port object, err well, almost anyway. You need to wait for someone to connect to it (thus making a connection), so you might want something like this:
while (!data.isConnected()) { if (IsKeyPressed(KEY_ESCAPE)) break; font.drawText(0, 0, "Connecting..."); FlipScreen(); }
Which would wait until someone connects to 'data', but allowing you to press escape if you want to cancel.
Now that a connection is made, send a hello message, like so:
if(data.isConnected())
{
// send a hello message
data.write(CreateByteArrayFromString("hello: Hi, you've connected to " + GetLocalAddress()));
}
Now pretend you've started playing multiplayer pong.
data.write(CreateByteArrayFromString("pongx: " + pong.x));
Client example
Now you need a client. Almost the same thing, really.
var font = GetSystemFont(); var port = 1234; var address = "213.13.5.94"; // your server's ip, you can get this from using irc, and the command: // /dns theirnickname var data = OpenAddress(address, port); while (!data.isConnected()) { if (IsKeyPressed(KEY_ESCAPE)) break; font.drawText(0,0, "Connecting..."); FlipScreen(); } data.write(CreateByteArrayFromString("hello: Hi, I've just connected to you using: " + GetLocalAddress())); data.write(CreateByteArrayFromString("pongx: " + pong.x));
Anyway, you now need to check for "pongx: " each time you are sent something.
if(data.getPendingReadSize()) { var txt = data.read(data.getPendingReadSize(); txt = CreateStringFromByteArray(txt); if(txt.indexOf("pongx: ") == 0) pong.x = parseInt(txt); // I think, hehe }
I bet this method would be really, err bad, because I've made it so the server controls where pong.x is... oh well, you get the idea at least.
Special thanks goes to fenix. Without him, this doc wouldn't exist.
By Flikky (from the Sphere CHM, adapted and updated for the wiki.)

