Tag Archives: .NET

Connecting a node app using socket.io to a Windows Forms .NET client application

In previous posts, I developed a node.js application that could provide temperature updates to clients using socket.io. With renewed interest in .NET, I thought it would be interesting to see if I couldn’t build a Windows Form app client that could connect to socket.io interface and receive the temperature updates.

Construct a .NET App which Supports a Socket.io Connection

While targeting a Universal Windows project has perhaps more contemporary relevance, for this example, we’ll stick to the classic Windows Form application.

You’ll want to start a new Windows Forms Application, as selected from Visual C# – Windows – Classic Desktop template section.

Classic Desktop Windows Form Application

Classic Desktop – Windows Forms Application

After we’ve started a new project, we’ll need to add two nuget extensions: SocketIoClientDotNet and Json.NET by NewtonSoft.

SocketIoClientDotNet provides a .NET-based socket.io implementation, in this case the client-side interface – a server-side interface is also available. Use nuget to search out and install the library.

Nuget SocketIoClient Library

Install SocketIoClientDotNet from nuget

We also need to also nuget Json.NET, which will provide us tools to handle incoming socket.io data delivered in JSON format.

Nuget NewtonSoft Json.NET.jpg

Install NewtonSoft’s Json.NET from nuget

With the two extensions installed, we’ll want to go ahead and build out the basic UI in a Windows Form. For this example, we’ll want to press a button to initiate our socket.io client, find out if we connected (putting the status in a TextBox) and then, if connected, display the temperature our node app will be sending us (within another TextBox):

Our Windows Form Application

The SocketIoClient’s Windows Form

While there are better ways to handle the connection, for the sake of simplicity, I’ve put the grunt work within the socketIoManager method – which aside from instantiating the socket.io connection, provides the basic socket.io On handlers to manage incoming events/data. About the only other thing mentioning is that any UI updates need to be managed by delegates because events received by the socketIoManager method are happening on a different thread than the UI thread, hence the need for the UpdateStatus and UpdateTemp methods:

Initialize and Handle Socket.io

Here’s a short video explaining the project:

 

 

 

 

Advertisements