0

I have to build a functionality where I can send custom event with websockets-sharp.

I made a function MakePacket that creates me a string like this ["draw:drawer:accept","{\"imei\":\"123\"}"] that I can send.

    public string MakePacket(string eventName, string data)
    {
        return JsonConvert.SerializeObject(new[] { eventName, data });
    }

So I want to do the same in the other direction. When there is an incomming event I want to convert this back to eventName and PayLoad.

So I create a data model:

public class PacketModel
{
    public string EventName { get; set; }

    public string PayLoad { get; set; }
}

And I tried to convert this with this function:

    public PacketModel OpenPacket(string data)
    {
        PacketModel packet = JsonConvert.DeserializeObject<PacketModel>(data);

        return packet;
    }

But this isn't working...

Does someone has an idea how I can do this?

Thank you

DerStarkeBaer
  • 669
  • 8
  • 28

2 Answers2

2

You can do something like this:

public static class sConnection
{
    public static WebSocket socket;
    public static bool connected = false;
    public static bool result = false;

    public static void Main()
    {
        socket = Connect();
        socket.Connect();


        while (!result) { }
    }

    public static WebSocket Connect()
    {
        var socket = new WebSocket(url: ""); //Your websoket enpoint

        socket.OnOpen += (sender, e) =>
        {
            isConnected = true;
        };

        socket.OnClose += (sender, e) =>
        {
            isConnected = false;
        };

        socket.OnMessage += (sender, e) =>
        {
            //Converting the event back to 'eventName' and 'Json'
            PacketHandler packetHandler = new PacketHandler();
            PacketModel packet = packetHandler.OpenPacket(e.Data);

            //Do something with the message

            result = true;
        };

        return socket;
    }
}
0

I create an example, how to work with WebSocket-Sharp and custom events like socket.io.

I post the example in my git repository:

Websocket-Sharp Custom Events

Thanks to @Evk for the help

DerStarkeBaer
  • 669
  • 8
  • 28