Link to home
Start Free TrialLog in
Avatar of jetbet
jetbetFlag for New Zealand

asked on

C# Driving a websocketsharp from GUI

I have created the following code to recieve data from a WebSocket, and convert the Json string to XML.

This is currently a Console application, but I want to move it onto a GUI with the socket listening on a separate thread.

Can someone give a quick example of how best to do this. From what I see online it looks as though creating a separate class may be the way to go.

using WebSocketSharp;
using Newtonsoft.Json;


namespace WebSocketSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ws = new WebSocket("ws://xxx.xxx.xxx.xxx")) //Server address
            {
                ws.OnMessage += (sender, e) => ConvertToXml(e.Data);
                ws.Connect();
                ws.Send("BALUS");
                Console.ReadKey(true);
            }
        }

private static void ConvertToXml(String json)
        {
          //  String fileName = String.Format("{0:yyyyMMdd_HHmmffff}", DateTime.Now) + ".xml";

            XmlDocument myXmlNode = JsonConvert.DeserializeXmlNode(json, "root");

            String race = GetElementValue(myXmlNode, "root/raceNumber");
            String first = GetElementValue(myXmlNode, "root/runners[position = '1']/RaceBookNumber");
            String second = GetElementValue(myXmlNode, "root/runners[position = '2']/RaceBookNumber");
            String third = GetElementValue(myXmlNode, "root/runners[position = '3']/RaceBookNumber");
            String fourth = GetElementValue(myXmlNode, "root/runners[position = '4']/RaceBookNumber");

            Console.WriteLine("Race " + race + " : " + first + " : " + second + " : " + third + " : " + fourth);



          //  myXmlNode.Save(fileName);
        }

        public static string GetElementValue(XmlNode _parent, string _xPath)
        {
            try
            {
                if (_parent == null)
                {
                    return "";
                }
                else
                {
                    XmlNode lNode = _parent.SelectSingleNode(_xPath);
                    if (lNode != null)
                    {
                        return lNode.InnerText;
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }  

Open in new window

Avatar of jetbet
jetbet
Flag of New Zealand image

ASKER

I have created the following class
public class WebSocketClient
    {
        SynchronizationContext uiContext;
        String host = "";
        Form1 form = null;
        public WebSocketClient(Form1 _form,String _host)
        {
            form = _form;
            host = _host;
        }


        public void Connect(object state)
        {
            uiContext = state as SynchronizationContext;

            UpdateRunnerStatus("Connecting to " + host);

            using (var ws = new WebSocket(host))

            {
                ws.OnMessage += (sender, e) => ConvertToXml(e.Data);
                ws.Connect();

                UpdateRunnerStatus("Connection is live = " + ws.IsAlive.ToString());

                ws.Send("BALUS");
              
            }
        }

        private void ConvertToXml(String json)
        {
            String fileName = String.Format("{0:yyyyMMdd_HHmmffff}", DateTime.Now) + ".xml";
            XmlDocument myXmlNode = JsonConvert.DeserializeXmlNode(json, "root");
            String race = GetElementValue(myXmlNode, "root/raceNumber");
            String first = GetElementValue(myXmlNode, "root/runners[position = '1']/RaceBookNumber");
            String second = GetElementValue(myXmlNode, "root/runners[position = '2']/RaceBookNumber");
            String third = GetElementValue(myXmlNode, "root/runners[position = '3']/RaceBookNumber");
            String fourth = GetElementValue(myXmlNode, "root/runners[position = '4']/RaceBookNumber");

            UpdateRunnerStatus("Race " + race + " : " + first + " : " + second + " : " + third + " : " + fourth);

         //   Console.WriteLine("Race " + race + " : " + first + " : " + second + " : " + third + " : " + fourth);



            myXmlNode.Save(fileName);
        }

        private void UpdateRunnerStatus(String _data)
        {
            try
            {
                uiContext.Post(new SendOrPostCallback((o) =>
                {
                    form.UpdateListBox(_data);
                }
                                                ), null);
            }
            catch
            {

            }

        }

        public static string GetElementValue(XmlNode _parent, string _xPath)
        {
            try
            {
                if (_parent == null)
                {
                    return "";
                }
                else
                {
                    XmlNode lNode = _parent.SelectSingleNode(_xPath);
                    if (lNode != null)
                    {
                        return lNode.InnerText;
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }

Open in new window


and call it from the main form like this

SynchronizationContext uiContext = SynchronizationContext.Current;

            client = new WebSocketClient(this, "ws://xxx.xxx.xxx.xxx");  //Address redacted in this example but valid
            Task.Factory.StartNew(() => client.Connect(uiContext));

Open in new window


The client socket is created but does not stay open or return anything
The line " UpdateRunnerStatus("Connection is live = " + ws.IsAlive.ToString());" always shows IsAlive to be false
Avatar of jetbet

ASKER

The Connection is now showing as LIVE but the problem is that as soon as the function
public void Connect(object state)
        {
            uiContext = state as SynchronizationContext;

            using (ws = new WebSocket(host))
            {
                ws.OnMessage += (sender, e) => ConvertToXml(e.Data);
                ws.Connect();
                ws.Send("BALUS");     
            }
        }

Open in new window


completes the connection is broken.

So the question becomes

What call do I make to keep the connection alive and running in the background so it can continuously feed data to the GUI?
Avatar of jetbet

ASKER

ADMIN : Please close this question
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.