Click here to Skip to main content
Click here to Skip to main content
Go to top

SocketIO Programming in C# using SocketIO4Net Library

, 26 May 2013
Rate this:
Please Sign up or sign in to vote.
SocketIO - NodeJS desktop programming in C# using the SocketIO4Net library.

Introduction

Introduction to NodeJS

If you’re into web programming, you must have heard of nodeJS & its capabilities. NodeJS is a server side software system designed for developing highly scalable web applications. It was created by Ryan Dahl in 2009. NodeJS is a packaged compilation of Google’s V8 Engine, which is a javascript engine which ships with Chrome. V8 complies Javascript to native machine code before executing it instead of interpreting the code in a JVM. V8 optimizes the code during runtime & offers greater performance & inline caching. NodeJS allows developers to develop their front end & back end in javascript, enabling easy debugging & seamless integration. NodeJS implements asynchronous I/O meaning all the function calls/IO operations in NodeJS are non-blocking & hence it offers very high performance.

SocketIO

Everyone out there is crazy about NodeJS & SocketIO. What exactly is SocketIO? If you knew NodeJS before this tutorial, probably you must know what SocketIO is.  SocketIO is simply a javascript library for developing realtime web applications such as chat programs & stock market monitors, which must always keep an ‘always on’ connection with the server in order to deliver content. SocketIO has 2  parts;  a client side library for the web browser & a server side library for NodeJS. Like NodeJS, its API is also event driven.  SocketIO uses Websocket protocol mainly for content delivery. But, it can modify itself automatically as per the requirements & has fancy features like broadcasting to all clients, storing individual data about each client etc. 

Background

If you’ve ever googled for SocketIO tutorials, you must’ve noted that there are no real tutorials on desktop programming languages with SocketIO. I wanted to make an application for controlling my home automation system from my laptop. My current implementation uses NodeJS+Express+SocketIO & I’m able to control everything using a web interface. Out of curiosity, I wanted to make a desktop application for the same. I didn’t had the patience to redesign my backend because it was working fine & I didn’t wanted to modify my front end also. So, the solution was to mimic a SocketIO client without a browser. I googled for like an hour & I found a bunch of tutorials on SocketIO on Java. They were good. But honestly I don’t think Java goes good with Windows. I wanted a more pure approach & I couldn’t find one. But, I came across SocketIO4Net library by J.W Stott on CodePlex. But then also i couldn’t find any good resources. But, there is an awesome example code by J.W Stott in SocketIO4Net page. Making it as a base, i tried making an example program myself. Like all SocketIO tutorials out there, I’ve started making a chat program.

This tutorial assumes that you have installed NodeJS & SocketIO on your machine & you also has Visual Studio 2012. To install SocketIO4Net on your Visual Studio Project, install NuGet package manager from http://nuget.org/. After installing that extension, open up Visual Studio, goto Tools>Library Package Manager>Package Manager Console. On the package manager console, type the following command(without PM>) & SocketIO4Net Client library will be added to your project:

PM>Install-Package SocketIO4Net.Client

Server Side Code

Seriously, I don’t like complicating code & I don’t know whether this can be done in a much simpler way. But here goes:

Code:

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (msg) {
console.log('New Chat Message ', msg);
io.sockets.emit('txt',msg);
});
socket.on('disconnect', function () {
io.sockets.emit('User Disconnected');
});
socket.on('newuser', function (name) {
console.log(name,' Is Now Connected!');
io.sockets.emit('txt',name + ' is now online');
});
socket.on('exit', function (name) {
console.log(name,' Has Been Disconnected!');
io.sockets.emit('txt',name + ' is now offline');
});
}); 

I know! No fancy coding or complications! the base code for this was taken from an example at theSocketIO website. I modified it a little so that it’ll echo whatever message comes to it. This server is simply an echo server that broadcasts the message from its clients to all the connected clients. When a new user connects, it echoes that a new user has been connected. The client sends the username of the client & the server broadcasts it. Also, when a user sends a message, designated by “private message” event, the server will echo that also & the client receives it as “txt” event. When a user disconnects, the client will dispatch an “exit” event along with the name of the user, ther server echoes that the user went offline.

When you run this code, you’ll get the following screen:

NodeJS Chat Server Window 

The server logs all the messages from the clients. The code works on Ubuntu server 12.04LTS. The only modification required is that, the port must be changed because you might have Apache already listening to that port.If you’re using Ubuntu Server, you’ll get the following screen(I’m using PuTTY to communicate with my server over SSH) :

NodeJS Chat Server Program Output Ubuntu Server 12.04LTS

Client side

On the client side, I’ve created a C# Winforms application, created a couple of windows, threw in a bunch of textboxes & buttons & voila! We have a chat application! Ok, its not exactly like that. But, its easy! SocketIO4Net.Client is very similar to SocketIO client side for browsers. For example, for registering the event “txt”, which is emitted by the server on a new “private message” event, the code is:

socket.On("txt", (data) =>
{
String msg = data.Json.Args[0].ToString();
Console.Write(msg);
});  

What this code does is that, when a new event “txt” is emitted by the server,  it’ll parse out the message data that has been sent out & displays it on the console, as simple as that! Like this, you can register as many events as you can & each will be executed on their own threads.

Points of Interest

The drawback is that, even if this code is inside your form, it can’t modify any controls! Say for example, i have a Form1.cs file. I’ve put this just below the ‘InitializeComponent()’ of the form. The event will be registered, but the below code won’t work:

socket.On("txt", (data) =>
{
String msg = data.Json.Args[0].ToString();
textBox1.Text = msg;
Console.Write(msg);
}); 

Yes, it won’t work! But this will work:

socket.On("txt", (data) =>
{
String msg = data.Json.Args[0].ToString();
MessageBox.Show(msg);
Console.Write(msg);
}); 

This works because the MessageBox is not connected to the UI & hence it can be called from any thread. But, GUI controls on the other hand, are not! They run on their own threads & they require using lambda expressions inorder to make an anonymous delegate that will be executed in the UI’s own thread. Hence, for updating it, the following code must be used:

socket.On("txt", (data) =>
{
String msg = data.Json.Args[0].ToString();
if (textBox1.InvokeRequired)
   textBox1.Invoke(new Action(() => textBox1.Text += msg + Environment.NewLine));
Console.Write(msg);
});

This works as desired!

How to test the program

Make sure you’ve installed NodeJS & SocketIO. Run the “Start Sever.bat” inside the NodeJS folder of the project. Next, Compile the visual studio project & run it or, Open “SocketIO Group Chat Test.exe” inside the ‘Bin\Release’ folder of the project & enter the server details.

Server Details

If you’re running the server on the same machine, leave the settings as it is. Else if you’ve the server running on a different machine & port, just enter the ip address of that machine & the port on which the server listens to & click connect. You must get the following screen:

Chat Program

I’ve tried connecting 100 clients to my server & it didn’t even break a sweat! NodeJS rocks! This can easily be improved to match current chat programs in the market. The problem here is that, it only supports group chats. But, can be modified easily to make private chats. The SocketIO4Net.Client library is awesome! Thanks to J.W Stott for his efforts!

You can Fork the project from Git also: https://github.com/vsaravind007/SocketIO4Net.CS.Tutorial 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Aravind.V.S
Student
India India
I'm a engineering student specializing in Computer Science. I'm passionate about programming & electronics.

Comments and Discussions

 
QuestionVisual Basic PinmemberMrGod2U17-Oct-13 3:21 
SuggestionThe images don't load PinmemberHaBiX26-May-13 19:48 
GeneralRe: The images don't load PinmemberAravind.V.S28-May-13 3:09 
GeneralRe: The images don't load PinmemberHaBiX28-May-13 6:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 26 May 2013
Article Copyright 2013 by Aravind.V.S
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid