Skip to content

Instantly share code, notes, and snippets.

@jrusbatch
Created April 11, 2012 23:51
Show Gist options
  • Save jrusbatch/2363554 to your computer and use it in GitHub Desktop.
Save jrusbatch/2363554 to your computer and use it in GitHub Desktop.
$(function() {
connection = $.connection('/execute');
connection.logging = true;
connection.received(function(message) {
// Update html
});
connection.error(function(e) {
console.error(e);
});
connection.start({ transport: 'auto' });
$('#btn').on('click', function() {
if (!isConnected) {
connection.start();
}
connection.send(value);
});
});
public class ExecuteEndPoint : PersistentConnection {
/// <summary>
/// Handle messages sent by the client.</summary>
protected override Task OnReceivedAsync(string connectionId, string data)
{
var command = new ExecuteCommand
{
ClientId = connectionId,
Code = data
};
var message = Convert.ToBase64String(command.GetBytes());
var gateway = DependencyResolver.Current.GetService<RedisConnectionGateway>();
var redis = gateway.GetConnection();
return redis.Lists.AddLast(0, "queue:execute", message)
.ContinueWith(t => {
if (t.IsFaulted) {
return Send(new {
status = "error",
message = t.Exception != null ? t.Exception.Message : null
});
}
return Send(new { status = "ok" });
});
}
}
/// <summary>
/// Handle messages received from workers through Redis and broadcast them to the client with SignalR.</summary>
public void OnMessageRecieved(string key, byte[] message) {
// Retrieve the client's connection ID from the key
var parts = key.Split(new[] { ':' });
var clientId = parts[parts.Length - 1];
if (!string.IsNullOrEmpty(clientId)) {
var connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
var connection = connectionManager.GetConnection<ExecuteEndPoint>();
var data = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message));
// Forward the message to the user's browser with SignalR
connection.Broadcast(clientId, new { status = "ok", data = data });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment