Skip to content

Instantly share code, notes, and snippets.

@MagnusThor
Created October 17, 2013 10:35
Show Gist options
  • Save MagnusThor/7022681 to your computer and use it in GitHub Desktop.
Save MagnusThor/7022681 to your computer and use it in GitHub Desktop.
Simple XSocketsContorller and JS Client - Answers question from A.Kovalchuk .
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/XSockets.latest.min.js"></script>
<script>
var ws;
$(function () {
ws = new XSockets.WebSocket("ws://127.0.0.1:4502/HandlerController");
ws.on(XSockets.Events.open, function (connetion) {
console.log("This is the connection", connetion); // just sent to the JavaScript console
// When the contoller sends a message with the "topic"
ws.on("Hello", function (data) {
console.log("data", data);
$("<p>").text(data).prependTo("#messages");
});
// Test will give you a MessageClass ( see handler controller )
ws.on("Test", function (data) {
// note properties are case-sensetive
$("<p>").text(data.Text).prependTo("#messages");
});
});
// When the user hits the button #simple, send a mesage
$("button#simple").on("click", function () {
ws.publish("Hello", { message: 'Hello World!' });
});
// When the user hits the button #complex, send a mesage
$("button#complex").on("click", function () {
ws.publish("Test", { Text: 'Hello World via Model...' });
});
});
</script>
</head>
<body>
<button id="simple">Say Hello World! to 'Hello Action'</button>
<button id="complex">Send a 'object/model' to Test</button>
<div id="messages"></div>
</body>
</html>
using System;
using System.Collections.Generic;
using XSockets.Core.Common.Socket;
using XSockets.Core.Common.Socket.Event.Arguments;
using XSockets.Core.Common.Socket.Event.Attributes;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.XSocket.Model;
namespace Chat.Controllers
{
public class HandlerController : XSocketController
{
public HandlerController()
{
this.OnOpen += new System.EventHandler<OnClientConnectArgs>(HandlerController_OnOpen);
}
void HandlerController_OnOpen(object sender, OnClientConnectArgs e)
{
int i = 0;
}
// Changed the argument data to messae , as data is a reseved property
public void Hello(string message)
{
int i = 0;
this.SendToAll(message, "Hello");
// also consider passing back an object instead of the plain "sting"
//this.SendToAll(new {message = message, date = DateTime.Now}, "HelloObj");
// will be ws.subscribe("HelloObj", function().... in the Js Client
}
// Im replacing string message with a simple model to just show you the recomended way
[HandlerEvent("Test")]
public void Test(MessageClass message)
{
int i = 0;
this.Send(message, "Test");
}
}
public class MessageClass
{
public string Text { get; set; }
// Just add more properties her...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment