C# WebSocket-Sharp, Make it more smart

2020. 4. 13. 04:03Go

반응형

The WebSocket-Sharp's data sending and receiving events are simple and could be only usage of first demension.

So, We can try to make it more high level for us.

 

WebSocket-Sharp supports each one event that receiving and sending.

If we try to use only this two methods,then that's too hard and difficult for us to so, we give up the coding.

 

In this post, I will make only two classes and one interface.

here, make 'WsClient' class.

 

WsClient.cs

    public class WsClient
    {
        private static WebSocket socket = new WebSocket(Http.Request.SocketURL);
        private static Dictionary<string, EventHandler<MessageEventArgs>> events = new Dictionary<string, EventHandler<MessageEventArgs>>();
        public WsClient(Action<ErrorCode> ErrorHandler)
        {
            socket.Connect();

			//It just a sample. It must not work your computer
            On(Headers.Error.ToStringValue(), (packet) => //The Simple Communication
            {
                int codeValue;
                if (!int.TryParse(packet.Body, out codeValue) || !Enum.IsDefined(typeof(Packet.ErrorCode), codeValue))
                {
                    ErrorHandler(Packet.ErrorCode.WrongCode);
                    return;
                }

                Packet.ErrorCode code = (Packet.ErrorCode)codeValue;

                //Pass error handler
                ErrorHandler(code);
            });
        }
        public void On(string eventName, Action<IPacket> receiver)
        {
            if(events.ContainsKey(eventName))
            {
                socket.OnMessage -= events[eventName];
                events.Remove(eventName);
            }
			
            events.Add(eventName, (sender, e) =>
            {
            	//This sample must not work your computer and project.
                var splited = e.Data.Split('@');
                if (splited[0] == eventName)
                {
                    var receive = new SocketPacket.Receive(splited[1], splited[2]);
                    receiver(receive);
                }
            });

            socket.OnMessage += events[eventName];
            
        }

        public void Emit(IPacket packet)
        {
            socket.Send(packet.ToPacket());
        }

    }

Ah, it's too long to explain this.

private static Dictionary<string, EventHandler<MessageEventArgs>> events = new Dictionary<string, EventHandler<MessageEventArgs>>();

This variable saves all events that we put our events to 'On'.

For instance, On("HelloEvent", someEventHandler); will be saved in events, we can get this events like this events["HelloEvent"].

The Emit gets only IPacket parameter.

We can make the method short use the parameter that kind of interface.

 

SocketPacket.cs

    public interface IPacket
    {
        Headers Header { get; }
        string Body { get; }
        byte[] ToPacket();
    }
    public enum Headers
    {
        Error = 0,
        Join = 11,
        Leave = 12,
        Create = 13,
        Broadcast = 21,
        BroadcastAudio = 22,
        Participants = 23,
    }

First, let's see some headers and packet. It easy to understand, pass.

    public static class SocketPacket
    {
        public class Broadcast : IPacket
        {
            
            public Headers Header { get; private set; }
            public string Body { get; private set; }
            public Broadcast(string message)
            {
                if(message == null)
                    message = "";
                
                Header = Headers.Broadcast;
                Body = message;
            }
            
            public byte[] ToPacket()
            {
            	//Simple way to seperate headers and bodies
                var packet = $"{Header.ToStringValue()}@{Body}";
                return Encoding.UTF8.GetBytes(packet);
            }
        }
}

and then, we made a class that contains IPacket. So, We can pass this class instance to WsClient's Emit.

It's done. well, we made this code smart and clean just write a few more codes.

 

Let's try it on main class.

 

Main.cs

        private void errorSocketHandler(Packet.ErrorCode code)
        {
            switch (code)
            {
                case Packet.ErrorCode.ErrorBlablabla:
                	//Error handling Blablabla
            }
        }

make some error handler, and add 'On' event and 'Emit' event.

client.On(Headers.Broadcast.ToString(),(packet) =>
{
	MessageBox.Show(packet.Body);
});

client.Emit(new SocketPacket.Broadcast("Hello~"));

It might not work on other circumstance (We didn't make the Socket server)

 

Remember, It just a way to use WebSocket-Sharp smarter. Not a guide book.

 

Thank you for reading.

반응형