Skip to content

Getting started with the Server

Daniel B edited this page Oct 4, 2016 · 5 revisions

Initialising.

To create the server just initialise a new mphx.server.Server. First pass the IP for the server and then the port. The IP should generally be 127.0.0.1 if you don't know what changing that means. The port can be anything that isn't claimed by the computer. The clients will automatically be able to connect.

var serverObject = new mphx.server.Server("127.0.0.1",8000);

Keeping track of players

To keep track of players, nothing is done automatically, however it is easy to manage them. You can create a player map that maps a Connection to player data. This means that it is easy to get the player a connection belongs to. The Player class can of course be anything you like, however it is simpler to keep this as a small data object, rather than a large object created by your graphics library. typedef PlayerData = { x: Int, y: Int, id: String }

public var players:Map<mphx.tcp.Connection,PlayerData>;

Sending a message to a specific client

Sending a message to a specific client is quite easy, you just need to have access to it's connection/client socket. From that, you can just call clientConnection.send("EventName",{data:123}). This connection can be accessed by a 'receive' event call, where the second function argument is the socket. Thus, to respond to a sent message, just use this.

serverObject.events.on("Event Name",function (dataFromClient,sender){
    //Reply to the sender.
    sender.send("Response",{"responseData":"Hello to you to!"})
});

The same goes with accessing a player from a map mentioned above. Just .get( from the map and call .send(

Sending a message to every client

In order to send a message/event to every client connected to the server, the broadcast method should be used. serverObject.broadcast("Event Name",dataToBeSent)

Listening to messages from the client

In order to respond to a message from the client, events are used.

serverObject.events.on("Event Name",function (dataFromClient,sender){

});

###Detecting a disconnection. Servers have a variable called onConnectionClose which is of type IConnection->Void. This is a variable that points to a function with one IConnection argument, and returns nothing. (more info here). The IConnection argument will be the connection that was terminated. An example of using this is shown below.

server.onConnectionClose = function (reason:String, connection:IConnection){
    trace("A client disconnected from the game. "+reason);
}

Clone this wiki locally