Wednesday, November 25, 2015

.NET WebSocket Libraries

WebSockets are awesome, and you should be using them. If you are working with .NET, then there are some very easy to consume libraries to help you host a WebSocket server or connect as a WebSocket client.

Below is a complete chat server and client made using ONLY these two libraries.

Server Demo

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using Fleck;
 
namespace WebSocketDemo.Server
{
    public static class Program
    {
        private static readonly ConcurrentDictionary<int, IWebSocketConnection> Connections
            = new ConcurrentDictionary<int, IWebSocketConnection>();
 
        public static void Main(string[] args)
        {
            var port = args.FirstOrDefault() ?? "8181";
            var uri = string.Format("ws://0.0.0.0:{0}/", port);
 
            Console.WriteLine("WebSocketDemo.Server");
            Console.WriteLine("========================================");
            Console.WriteLine("Type a message, or an empty line to exit");
            Console.WriteLine("========================================");
 
            using (var server = new WebSocketServer(uri))
            {
                var idSeed = 0;
 
                server.Start(connection =>
                {
                    var id = Interlocked.Increment(ref idSeed);
 
                    connection.OnOpen = () => Write(id, "Open: {0}", id);
                    connection.OnClose = () => Write(id, "Close: {0}", id);
                    connection.OnError = ex => Write(-1, "Error: {0} - {1}", id, ex.Message);
                    connection.OnMessage = m => Write(id, "User {0}: {1}", id, m);
 
                    Connections.TryAdd(id, connection);
                });
 
                while (true)
                {
                    var line = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                        break;
 
                    Write(0, "Admin: {0}", line);
                }
            }
        }
 
        private static void Write(int id, string format, params object[] args)
        {
            var message = string.Format(format, args);
 
            if (id != -1)
            {
                foreach (var connectionPair in Connections)
                {
                    if (!connectionPair.Value.IsAvailable)
                        continue;
 
                    if (connectionPair.Key == id)
                        continue;
 
                    connectionPair.Value.Send(message).Wait();
                }
            }
 
            var consoleMessage = string.Format(
                "{0} - {1}",
                DateTime.Now.ToLongTimeString(),
                message);
 
            Console.WriteLine(consoleMessage);
        }
    }
}

Client Demo

using System;
using System.Linq;
using WebSocket4Net;
 
namespace WebSocketDemo.Client
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var port = args.FirstOrDefault() ?? "8181";
            var uri = string.Format("ws://localhost:{0}/", port);
 
            Console.WriteLine("WebSocketDemo.Client");
            Console.WriteLine("========================================");
            Console.WriteLine("Type a message, or an empty line to exit");
            Console.WriteLine("========================================");
 
            using (var client = new WebSocket(uri))
            {
                client.Opened += (s, e) => Write("Open");
                client.Error += (s, e) => Write(e.Exception.Message);
                client.Closed += (s, e) => Write("Close");
                client.MessageReceived += (s, e) => Write(e.Message);
 
                client.Open();
 
                while (true)
                {
                    var line = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                        break;
 
                    client.Send(line);
                }
            }
        }
        
        private static void Write(string s)
        {
            var consoleMessage = string.Format(
                "{0} - {1}",
                DateTime.Now.ToLongTimeString(),
                s);
 
            Console.WriteLine(consoleMessage);
        }
    }
}

Output

WebSocketDemo.Client
========================================
Type a message, or an empty line to exit
========================================
4:39:23 PM - Open
4:39:23 PM - Open: 2
Hello!
4:39:32 PM - User 2: Howdy.
How are you?
4:39:39 PM - User 2: Meh.
4:39:48 PM - Admin: Seriously?
4:39:53 PM - User 2: Yes.
KK, bye bye!
4:40:01 PM - User 2: Peace out.

WebSocketDemo.Client
========================================
Type a message, or an empty line to exit
========================================
4:39:23 PM - Open
4:39:30 PM - User 1: Hello!
Howdy.
4:39:35 PM - User 1: How are you?
Meh.
4:39:48 PM - Admin: Seriously?
Yes.
4:39:57 PM - User 1: KK, bye bye!
Peace out.
4:40:16 PM - Close: 1

WebSocketDemo.Server
========================================
Type a message, or an empty line to exit
========================================
11/25/2015 4:39:19 PM [Info] Server started at ws://0.0.0.0:8181/
4:39:23 PM - Open: 1
4:39:23 PM - Open: 2
4:39:30 PM - User 1: Hello!
4:39:32 PM - User 2: Howdy.
4:39:35 PM - User 1: How are you?
4:39:39 PM - User 2: Meh.
Seriously?
4:39:48 PM - Admin: Seriously?
4:39:53 PM - User 2: Yes.
4:39:57 PM - User 1: KK, bye bye!
4:40:01 PM - User 2: Peace out.
4:40:16 PM - Close: 1
4:40:26 PM - Close: 2

Enjoy,
Tom

1 comment:

Real Time Web Analytics