Setting up your first Socket

The first thing you should do to familiarize yourself with the library is to set up a simple easyXDM.Socket class, which will allow cross domain communication with messages going both from the consumer to the provider, and the other way around.

A socket is is quite similar to a regular TCP-socket, you send a stream down it, and it will exit through the other end of the socket. This is the same with easyXDM, a socket will accept a text string, and make sure that this exits through the other end, even if the ‘sockets’ residere on different domains. The Socket class wraps the needed behaviors needed to make up a suitable ‘network-stack’ in the browser.

With this example it is expected that you have access to both domains (testing on the same domain is just fine (does not work in IE6/7 due to the NameTransport), but its more fun if its on separate ones 🙂 ), and that you have uploaded the easyXDM.debug.js file, and the name.html file to the directory /easyxdm/.

We’ll start with a simple HTML5 compatible document which will be the basis for both the provider and the consumer.

<!doctype html>
        <title>easyXDM.Transport test</title>
        <script type="text/javascript" src="/easyxdm/easyXDM.debug.js"></script>

The provider

Now, in the body of the provider-document, which we’ll call provider.html, place the following code

var socket = new easyXDM.Socket({
    onMessage: function(message, origin){
        alert("Received '" + message + "' from '" + origin + "'");
        socket.postMessage("Indeed it does!");

As you can see, the provider has no knowledge about the consumer, but it is able to control the origin of the incoming messages via the ‘origin’ parameter.

We include an onMessage function that will receive incoming messages, and which in this case will alert the message before sending a message back to the consumer.

The consumer

In the body of the consumer-document place the following code

var socket = new easyXDM.Socket({
    remote: "http://remotedomain/provider.html",
    onMessage: function(message, origin){
        alert("Received '" + message + "' from '" + origin + "'");
    onReady: function() {
        socket.postMessage("Yay, it works!");

Things to note here are

  1. We set the ‘remote’ parameter to point at provider.html
  2. We include a method ‘onReady’ that will be executed once the Socket is verified to be up and running

And thats it. The above code is all you need to send and receive messages,  and also forms the pattern that all other code samples follow.

Now, if you got this working, why don’t you take a minute to read the documentation? Copy-pasting code is nice, but its always better to actually know what is going on ;).

This entry was posted in Getting started and tagged , , , , , , , , , , , , , . Bookmark the permalink.