Skip to content
Martin McDonough edited this page Apr 3, 2015 · 1 revision

Networking with TurboSphere is not difficult. The full power of network sockets is exposed, but in a safe and simple way.

The following is a simple server and client example that demonstrates basic networking.

Note that while TurboSphere fully supports networking, it is up to the game to implement or provide the protocol. A good place to start when considering how to send information between the client and server in your game would be JSON. TurboSphere fully supports JSON natively, and a json implementations exist for many languages.

API

The TurboSphere networking API can be found in the Function List. A basic explanation of all the objects exists there.

Example

Server Code

function game(){
  var listener = new ListeningSocket(8192); //A constructor, otherwise a synonym for ListenOnPort
  while(true){
    // Will return null if no incoming connections
    var new_socket = listener.accept();
    if(new_socket){
      // Wait until we actually have something to read.
      while(!new_socket.getPendingReadSize()) Delay(10);
  
      var buffer = new_socket.read(new_socket.getPendingReadSize());
  
      // Write out whatever we receive, just to prove it actually happened.
      var logfile = new RawFile("out.log", true);
      logfile.write(buffer);
      logfile.close();
      new_socket.close();
  
      break;
    }
    Delay(10);
  }
}

Client Code

RequireSystemScript("turbo/bytearray.js");

function game(){
  var socket = new Socket("127.0.0.1", 8192);

  if(!socket.isConnected()) throw "Are you sure the server is running?";

  // The `.buffer' is because ByteArrays are actually UInt8Array's under the hood. This won't be necessary at some point in the future, but it will still be valid.
  socket.write(CreateByteArrayFromString("Hello, server!\n").buffer); 

  while(socket.isConnected()) Delay(10); // The server function should drop us pretty quickly.

  Abort("Success!");
}

When both these games are run from the same machine, the server game will log "Hello, server!" to file. In an actual game, you would properly need to parse the information. You can keep connecting again and again to the same server with this example.

Making a Dedicated Server

Some games have a dedicated server program, which is not hosted from the main game. This example is one of them. But it still opens a window, and still listens for windowing events. Why bother with that?

If you make a copy of the TurboSphere binary directory and remove the Sapphire and InputSDL2 plugins, it won't have a window. Since no Sapphire or Input functions are called, it will still run fine. You can go even further and remove the Cinnamon audio plugin from the server's plugin folder.

Clone this wiki locally