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.
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.
We also need to also nuget Json.NET, which will provide us tools to handle incoming socket.io data delivered in JSON format.
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):
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:
Here’s a short video explaining the project: