ListenOnPort

From Spheriki

Jump to: navigation, search

Waits for a connection on the given port on the current computer, and returns a socket.


Contents

Usage

Socket ListenOnPort(port);
  • port number, non-negative. The port on this computer that any clients should be connecting to.
  • Socket is returned, representing the communication link between this computer and the computer that is making the connection.


Examples

For best results, run this while trying out the client example given on the OpenAddress() reference page.

var font = GetSystemFont();

function game()
{
  var port = 12345;  // Same as in OpenAddress() example
  var done = false;
  
  while (!done)
  {
    // 1. Listen for incoming connections.
    var sock = ListenOnPort(port);
    
    // 2. Wait for the connection to take place.
    while (!sock.isConnected() && !done)
    {
      if (IsKeyPressed(KEY_ESCAPE))
        done = true;
      font.drawText(0, 0, "Waiting for a client... (press ESC to cancel)");
      FlipScreen();
    }
    
    // 3. If connected, send our data.
    if (sock.isConnected())
    {
      var msg = "Hello everybody! You just connected to " + GetLocalAddress() + "!";
      sock.write(CreateByteArrayFromString(msg));
      
      // 4. Close the socket when we're done.
      sock.close();
    }
  }
}

This simple server will listen on port 12345 (step 1). It will then wait until a client connects (step 2). Once a client has connected, this server will send a message to them (step 3), and then close the socket (step 4). It will repeat this process until ESC is pressed.

In short, this server waits for clients to connect, and sends them a small message in return.


Notes

  • In a client-server arrangement, this function is typically used on the server's side to wait for a connection from a client. The client will usually connect using the OpenAddress() function.
  • This function is asynchronous. The game will continue to run after this function is called, even if the connection hasn't gone through yet. See the example for why this is useful.
  • Sphere uses traditional BSD sockets underneath the surface, so it can be used to communicate with almost any other network-enabled application on almost any other computer in the world. It can even be used to obtain files via HTTP, like webpages. Such techniques are beyond the scope of this reference page.
  • For further information, see docs/development/network.txt of your Sphere installation.


See also

Personal tools