Just recently we have made some improvements on the JavaScript API’s that’s enables XSocketers to deal with the publish/subscribes patterns of WebSockets development upon the XSockets WebSocket Server for Microsoft Windows, it simplifies the whole thing a bit more. in this blog post I will try to explain a common scenario that you probably will face when developing things on out WebSocket Server.
Before I start I will send some greetings thanks to all of of you that has been sending us good feedback, thank you very much!
Lets start then, first of all I chosen to use a non generic WebSocketHandler – MyCustomHandler, it consists of a single method named OnBroadcast note also that it is exposed with a help of an HandlerEvent attribute
{
[Export(typeof(IXBaseSocket))]
public class MyCustomHandler : XSockets.Core.Handlers.Generic
{
/// <summary>
/// HandlerEvent for OnBroadcast using the Message Model
/// </summary>
/// <param name="message"></param>
[HandlerEvent("OnBroadcast")]
public void OnBroadcast(Message message)
{
// Just to illustrare how to create and send (publish) a new event
var replyMessage = new XSocketEvent<Message>
{
Event = "OnBroadcast",
Data = message
};
var json = replyMessage.Serialize(); // Serialize the XSocketEvent<Message> as JSON
// Itterate trough all XNodes ( Clients) and send the "message" (replyMessage)
foreach (var xNode in XNodes)
{
// You can access each XNode (client) payload to do filtering etc. here by using XNode.XSocket.XSocketPayLoadEvent.Data ...
xNode.Value.XSocket.Send(json);
}
}
}
}
As you see the HandlerEvent is strongly typed saing that we expect an Message , The message is a simple model as shown below.
{
[Serializable]
[DataContract]
public class Message
{
[DataMember]
public string Text { get; set; }
}
}
This is a much more convenient way of dealing with the inbound data compared to calling the underlying XSocketsPayloadEvent of the XNode itself, as shown below
This is what we would have been forced to to if our HandlerEvent hasn't been strongly typed.
So, lets have a look at at how we connect to the WebSocket (WebSocketHandler) using the JSAPI
var wsSocket = new $$.xWebSocket("ws://127.0.0.1:4502/XSocketHandler.PubSubSample.MyCustomHandler", null);
wsSocket.bind("open", function () {
console.log("wsSocket WebSocket Handler is open!");
});
wsSocket.bind("close", function () {
console.log("wsSocket WebSocket Handler is closed!");
});
The snippet above connects us to the WebSocket Handler (server as well ) , as you see we are pointing out our custom handler (XSockets.PubSubSample.MyCustomHandler) , we are also establishing a subscription to the open and close events of the WebSocket by using the .bind (subscribe) method , these two bindings are is an subscription.
Publishing data to the WebSocket handler ( Pub scenario)
We have made some improvements to the publishing areas of the JsAPI, those has been a little confusing to some, so I will try to explain this a bit as follows.
Lets say that we have a button in our web-page named (id’d) btnStart, and by using jQuery a event handler is created for this particular button (btnStart)
// Create a new WebSocketMessage that corresponds to the OnBroadcast method inside our CustomHandler
var msgMessage = new $$.WebSocketMessage("OnBroadcast");
// Add A JSON Object to the WebSocketMessage (Message data)
msgMessage.AddJson({
Text: $("#message").val()
});
// Different ways of triggering / publishing messages to a WebSocket Handler
wsSocket.trigger(msgMessage.PayLoad());
wsSocket.trigger(msgMessage.Message);
// Add a WebSocketMessage , add an event handler for onCompleted(args)
wsSocket.trigger(msgMessage.Message, TriggerOnBroadcastCompleted);
// Create a new WebSocketMessage 'OnBroadcast", add the 'data' JSON, add an event handler for onCompleted(args)
wsSocket.trigger("OnBroadcast", { Text: $("#message").val() }, TriggerOnBroadcastCompleted);
});
As you see a WebSockets message is created by using WebSocketMessage , as well as we adds a JSON object using .AddJson(json) , in out case it reflects XSockets.Models.Message class show above, the JSON representation would look as below;
The complete JSON Representation of out WebSocketMessage is an important thing to notice, the JSON representation of the complete Message has the following JSON representation
event:"OnBroadcast",
data: { Text:"Hello World"}
}
The event property is the key to the HandlerEvent routing withing the server, but notice this is something the the WebSocketMessage will give you. As you see in the JavaScript snippet just above there is a couple of diffent ways of publish (trigger) messages to the server.
Publish by using the Message property of the WebSocketMessage ( Publish an existing message object)
By adding a second argument ( as shown below) , you are able to attach en event handler that will be when the messages is published ( triggered)
The event handler may looks like this, the argument (eventObject) is the actual WebSocketMessage published (triggered)
}
The third and most requested alternative is as follows ,in this case we don’t need to prepare any WebSocketMessage , we just need to pass the name of or Message ( i.e Onbroadcast as the first argument, then we'll pass the data (JSON) that reflects our model, I’ll think you’ll get the picture here.
Subscribing data send by a WebSocket handler
By using the .bind mehod you are able to subscribe to inbound messages at the client side, This is reminiscent of how we handle things in our WebSockets handlers. And can briefly be explained as follows.
Lets say that we also listens to the OnBroadcast WebSocketMessage ( note that a you can of course listen to messages not initialized by your client) , so lets go
});
The pice of code above show how you establishes a subscription for inbound messages named “OnBroadcast” , the eventObject (message) will in this example consist of a JSON representation of our Model (Message) , just do be clear I’ll drop the sting representation of the eventObject (message)
We would roughly deal with it in this manner;
Inspired by the astute jQuery way of dealing with events and experiences of our own implementations you can now do the following:
One
Triggers the event once and stops subscribing after first hit.
// do stuff once
});
bind(event,options,fn)
By passing options to the bind method we are able to limit the number of times we listen (subscribes) to the event, by specifying a "counter” object as shown below.
Counter: {
Messages: 3,
Completed: function () {
wsSocket.unbind("OnBroadcast");
}
}
};
wsSocket.bind("OnBroadcast", options, function (message) {
// Do Stuff 3 times , then execute "Complete"
});
Summary
The things mentioned above are a few new things added to the JsAPI , making the JavaScript related development on XSockets.net a bit more easier, it’s a subset of the forthcoming release.
Yours sincerely
Magnus Thor, Team Sockets
ps.
If you want test the new version of jXSockets (JsAPI) let us know and we will send you a copy, it' is of coz compatible with your existing stuff on XSockets.

0 kommentarer:
Skicka en kommentar