This code is currently being used in a development / preview environment, and is under active development.  Sure there’s more to do and probably a few bugs I haven’t found yet…and all of the usual disclaimers, ymmv, blah blah blah.  Given this, you still should be able to get a working sample as is.

Documentation
This documentation is broken into the following pages:

  • This document – General summary ( a work in progress).
  • TestSetup – how to get your local environment up to speed.
  • EventData – details on event data messages (json payload from socket.io)
  • Namesapce – details on namespace usage

Configuration 
You’ll need node.js and its associated modules & files configured for your local environment, please refer to this test setup page to see how. 

To run the sample TestProject code

  1. Run ..\TestProject\node\startEvents.bat file – this will launch node.js & a Chrome client pointing to http://localhost:3000
    Adjust your firewall / access permissions as necessary, or alter the batch file if you’d rather run a different browser than Chrome. 
  2. Verify the output of the browser client text area and node.js console output (see the  docs for reference).
  3. Build the solution, and set TestProject as startup project – Start Debug (F5 or Ctrl+F5 w/o debug as you want)
  4. Verify the console out as show below.
    TestProject console output

image

  1. To exit the console, press ‘q’ then Enter, or to clear the console, press ‘c’ then Enter
  2. Run Callback example, press ‘b’
  3. Run Namespace sample, press ‘n’

Setup and Layout

..\TestProject is a sample console project to show usage of the SocketIO4Net.Client code.  The class TestSocketIOClient.Execute() method shows a sample connection and Emit/On event handlers. 

..\TestProject\node contains these files and usage:

  • appEvents.js – node.js application file will be running.
    • It requires three modules: optimist, express, and socket.io.
  • appEventsClient.html – browser markup &  javascript (socket.io connection)  sample that we’ll duplicate in our c# code sample.
  • startEvents.bat – batch file to start node.js and a chrome browser instance (alter the batch if like to run otherwise).

Details

Now that you have basic components setup and working, let’s get to the point.  I’ll assume that if your looking for .net client for Socket.IO, at this point you’re at least a little familiar with the following setup for Socket.IO

appEvents.js

// ***************************************************************
//    Socket.IO Client Handlers
// ***************************************************************
io.sockets.on('connection', function (socket) {

    socket.on('partInfo', function (data) {
        console.log('recv [socket].[partInfo]  data = {0} \r\n'.format(JSON.stringify(data)));
        data.Level = 3;
        io.sockets.emit('update', data);  // broadcast event to all clients
    });

    socket.on('simple', function (data) {
        console.log('recv [socket].[simple]  data = {0} \r\n'.format(data));
    });

    socket.on('messageAck', function (data, fn) {
        console.log('[root].[messageAck]: {0}'.format(JSON.stringify(data)));

        if (fn != 'undefined') {
            console.log('  sending ack message \r\n');
            fn('hello son, {0}'.format(data.hello)); // return payload
        }
        else {
            console.log(' ** expecting return function to call, but was missing?');
        }
    });

    socket.on('disconnect', function () {
        console.log('client disconnected [root] namespace');
        io.sockets.emit('clientdisconnected'); // broadcast event to all clients (no data)
    });

});

Every time a client connects with the socket.io server, a ‘news’ event will be sent to that connection.  As clients send ‘event1’ or ‘event2’ event messages, they will be logged to the console.

appEventsClient.html (script section)

$(document).ready(function () {

    var socket = io.connect(); // default connection url to current page

    socket.on('connect', function () {
        showMessage('client is connected');
        showMessage('sending [root].['partInfo'] to server');
        socket.emit('partInfo', { PartNumber: '1234', Code: 'C', Level: 1 });
    });
    socket.on('update', function (data) {
        showMessage('recv [root].[update] : ', data);
    });
    socket.on('event', function (eventLog) {
        showMessage('Arghhh - should not have received this message matey!');
        showMessage('recv [root].[event]', eventLog);
    });
    socket.on('clientdisconnected', function () {
        showMessage('recv [root].[userdisconnected]');
    });

    // *****************************************
    // *************  logger namespace ***********
    // *****************************************
    var logger = io.connect('/logger'); // namespace 'logger'

    logger.on('connect', function () {
        showMessage('client is connected namespace [logger]');
    });
    logger.on('event', function (eventLog) {
        showMessage('recv [logger].[event] : ', eventLog);
    });
});

On document.ready, the client connects with the socket.io server, and demonstrates sending and receiving data.

C# code Sample

public void Execute()
{
    Console.WriteLine("Starting TestSocketIOClient Example...");

    socket = new Client("http://127.0.0.1:3000/"); // url to nodejs 
    socket.Opened += SocketOpened;
    socket.Message += SocketMessage;
    socket.SocketConnectionClosed += SocketConnectionClosed;
    socket.Error += SocketError;
    
    // register for 'connect' event with io server
    socket.On("connect", (fn) =>
    {
        Console.WriteLine("\r\nConnected event...\r\n");
        Console.WriteLine("Emit Part object");

        // emit Json Serializable object, anonymous types, or strings
        Part newPart = new Part() { PartNumber = "K4P2G324EC", Code = "DDR2", Level = 1 };
        socket.Emit("partInfo", newPart);
    });

    // register for 'update' events - message is a json 'Part' object
    socket.On("update", (data) =>
    {
        Console.WriteLine("recv [socket].[update] event");
        //Console.WriteLine("  raw message:      {0}", data.RawMessage);
        //Console.WriteLine("  string message:   {0}", data.MessageText);
        //Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
        //Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);
        
        // cast message as Part - use type cast helper
        Part part = data.Json.GetFirstArgAs<Part>();
        Console.WriteLine(" Part Level:   {0}\r\n", part.Level);
    });

    // make the socket.io connection
    socket.Connect();
}

The client Opened, Message, SocketConnectionClosed, and Error are not specifically required – but shown for completeness.  The ‘On’ event handlers and ‘Emit’ senders are the primary methods used.

Events

Registering for Socket.IO event messages in the .net client can be done using an lambda expression to an Action<IMessage> delegate instance in the .On(eventName, Action<IMessage>) method. 

Socket.IO messages sent to the c# client will only raise the generic OnMessage event if there is not a registered .On(‘eventName’) handler:

Socket.IO sends : 

socket.emit('news', { hello: 'world' });

Assume that the .net client has a registered event via socket.On(“news”, Action()), socket.OnMessage will not be raised for that “news” event.

Note that socket.Opened is not that same as socket.On(‘connect’) – ‘connect’ is an event message sent from the socket.io server.  Opened is from the .net client websocket ‘Opened’ event itself.  socket.On(‘connect’)  should contain any registration and/or connection setup that you need to pass to the socket.io server, as this may be called on a connection retry internal event.

Last edited Feb 7, 2012 at 4:46 AM by jstott, version 22

Comments

megadron Sep 26 at 8:10 AM 
TestProject not run.