WebSync Tutorials - Frozen Mountain
Note: these tuturials are for WebSync 2 only.

If you are using WebSync 3, you want our WebSync 3 tutorials.

WebSync 2 Tutorials




On-Demand: Publishers

Publishers let you publish data without the overhead of maintaining an active client connection. They can be invoked from almost anywhere in code and are a fast way to push server-side data to clients. In this tutorial, you will create a page that publishes data each time it is loaded.
Note that this tutorial is specific to .NET (C#), but the principles are the same for any language. For PHP, the publisher used in this tutorial is available as part of the WebSync On-Demand PHP download.

Prerequisites

Configuring your project

Before you can start coding, you need to have the correct project references.
  1. Add a reference to FM.WebSync.Core (available as part of the WebSync On-Demand .NET download).
  2. Add a reference to System.Runtime.Serialization (available as part of the .NET Framework).

Setting up a publisher

A publisher can send messages from anywhere in managed code.
  1. Create a new page called Publish.aspx and remove all HTML content.
  2. Create a Publisher in the code-behind.
  3. Call Publish() and pass in a Publication.
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Publish.aspx.cs" Inherits="Tutorials.Publish" %>
Code-Behind:
using System;
using System.Runtime.Serialization;
using FM.WebSync.Core;

namespace Tutorials
{
    public partial class Publish : System.Web.UI.Page
    {
        [DataContract]
        private class Data
        {
            [DataMember(Name = "text")]
            public string Text { get; set; }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Publisher publisher = new Publisher(
                "11111111-1111-1111-1111-111111111111", // your public or private key
                "localhost"                             // your domain
            );
            
            string result;
            bool success = publisher.Publish(new Publication()
            {
                Channel = "/test",
                Data = JSON.Serialize(new Data()
                {
                    Text = "Hello, world!"
                })
            }, out result);
            
            Response.Write(success ? "Published!" : "Publish failed: " + result);
        }
    }
}

Testing

Open up your client page in one window. Load this new page in another to see the publisher in action!