OpenAddress

From Spheriki

Jump to: navigation, search

Opens a connection with the computer with the given address, on the given port. Returns a socket that can be used to communicate over that connection.


Contents

Usage

Socket OpenAddress(address, port);
  • address String. Either the IP address of the computer to connect to, or the equivalent domain name.
  • port Number, non-negative. The port on the remote computer to connect to. The remote computer should be listening on that port with ListenOnPort().
  • Socket is returned, which can then be used to send and receive data to and from the remote computer.


Examples

For this example to work you will need to have another instance of Sphere running, but with the server example given in the ListenOnPort() page.

var font = GetSystemFont();

function game()
{
  var address = "127.0.0.1";  // local loopback interface, i.e. this machine
  var port = 12345;
  
  // 1. Start connection
  var sock = OpenAddress(address, port);
  
  // 2. Wait for connection to go through
  while (!sock.isConnected() && !IsKeyPressed(KEY_ESCAPE))
  {
    font.drawText(0, 0, "Connecting... (press ESC to cancel)");
    FlipScreen();
  }
  
  // 3. If connected, send and receive data.
  if (sock.isConnected())
  {
    var data = "";
    var read_size = sock.getPendingReadSize();
    
    if (read_size > 0)
    {
      data = sock.read(read_size);
      data = CreateStringFromByteArray(data);
    }
    
    while (!IsAnyKeyPressed())
    {
      font.drawText(0, 0, data);
      FlipScreen();
    }
    
    // 4. Close the open connection.
    sock.close();
  }
}

This example is one half of a client-server arrangement. It first opens a connection to address 127.0.0.1 (step 1), which means the local machine. This game will then wait for the connection to succeed before continuing (step 2). If the server program is running on the local machine at the same time, this client connection will succeed, and we can proceed to read some data from the server (step 3). Finally, we wrap things up by closing the connection (step 4).

In short, this client receives some string of data from the server, and displays it.


Notes

  • In a client-server arrangement, this function is typically used on the client's side to open a connection with the server. The server will be waiting for such a connection using ListenOnPort().
  • 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