Skip to content

Instantly share code, notes, and snippets.

@codeplanner
Created April 7, 2014 13:15
Show Gist options
  • Save codeplanner/10020074 to your computer and use it in GitHub Desktop.
Save codeplanner/10020074 to your computer and use it in GitHub Desktop.
Publish/Subscribe sample...
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.0.js"></script>
<script src="Scripts/XSockets.latest.js"></script>
<script>
var conn;
$(function() {
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/FRAInProcess');
conn.onopen = function() {
conn.on('process', function(d) {
console.log(d);
});
};
});
</script>
</head>
<body>
</body>
</html>
public class FRAInProcess : XSocketController
{
public void Process(ITextArgs args)
{
// This line will send the message to all clients
// that subscribe for the event defined in ITextArgs
this.SendToAll(args);
}
// NOTE: Personally I prefer to use strongly typed methods and avoid ITextArgs
// NOTE: ITextArgs is useful since they will accept anything, but you often know what to expect!
}
class Program
{
static void Main(string[] args)
{
using (var server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
server.StartServers();
Console.WriteLine("Started, hit enter to quit");
Task.Factory.StartNew(() =>
{
var i = 0;
while (true)
{
// OPTION NUMBER 1
//Get the instance from the client pool (only for publishing)
var client = XSockets.Client40.ClientPool.GetInstance("ws://127.0.0.1:4502/FRAInProcess", "*");
//Send an nonymous object, will be ok since you use ITextArgs that will swallow anyhting...
//We target the actionmethod "process" by passing that as the event
client.Send(new { Text = "An nonymous object, can be anything serializable", Value = i++ }, "process");
//_________________________________________________________________________________
// OPTION NUMBER 2 (really ugly and requires this code to run on server)
/*var ctrl = new FRAInProcess();
var json =
new {Text = "An nonymous object, can be anything serializable", Value = i++}.Serialize();
ITextArgs textArgs = new TextArgs {data = json, @event = "process"};
ctrl.Process(textArgs);*/
//_________________________________________________________________________________
//OPTION NUMBER 3 (still ugly but better than 2)
/*
Use a class instead of ITextArgs on the Process method in the controller.
Pass in an instance of that class into the method and use
this.SendToAll(customObject, "process");
That will also work... But the best and most clear way would be the comnination of 1 and 3.
Using the client to send it and a strongly typed object to make it more clear whats going on.
*/
Thread.Sleep(250);
if (i > 99)
i = 0;
}
});
Console.ReadLine();
server.StopServers();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment