-1

My program is a simple one, connecting to a Socket.IO server, emitting one message, then waiting for one in response. How can I keep it running to receive the message - it exits as soon as it has connected. This is my first C# program which hasn't been following a tutorial, so it's probably got quite a few bugs.

using System;
using System.Windows.Forms;
using System.Threading.Tasks;
using SocketIOClient;

namespace socketio
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // Application.Run(new Form1());]
            SocketIO client = new SocketIO("http://localhost:5000", new SocketIOOptions
            {
                EIO = 4
            });
            Connect();

            async Task Connect()
            {
                client.ConnectAsync();
                MessageBox.Show("Started");
                client.OnConnected += async (socketSender, b) =>
                {
                    await client.EmitAsync("data", new
                    {
                        deviceName = System.Environment.MachineName
                    });
                };

                client.On("popup", response =>
                {
                    var obj = response.GetValue(0);
                    string title = obj.GetProperty("title").GetString();
                    string message = obj.GetProperty("message").GetString();
                    MessageBox.Show(message, title);
                });

            }
        }
    }
}
    
        



    
    
homelyseven250
  • 154
  • 1
  • 3
  • 2
    You’ll have to make it do something forever. If it’s a console program then `Console.ReadLine()` may be enough for some cases, but unless there’s background threads it won’t really work. Also note that those visual styles etc are not needed in console programs, if anywhere. It would be easier to do this as a GUI application since they stay alive until closed by default. – Sami Kuhmonen Jul 10 '21 at 05:17
  • @SamiKuhmonen. I have now changed over to WPF - it looks a bit easier, and made a hidden window according to https://stackoverflow.com/a/6691090. Thanks for the hint! – homelyseven250 Jul 10 '21 at 07:06

1 Answers1

0

I've noticed, that you implemented an async method async Task Connect() and called that method without using await. The await is also missing on the client.ConnectAsync(); call. And since you commented out the Application.Run(new Form1()); call, the program exits after the Connect call. Try to call it after the await Connect(); call. That way, the program opens an empty window and stops, when you close that window.

Volkmar Rigo
  • 1,158
  • 18
  • 32