2

I'm in the early stages of writing a program to interface with an IP camera. A bit of code I wrote yesterday worked, but when I came back to it this morning it didn't. I know, I probably did something, but to the best of my memory it worked when I clicked debug before leaving and didn't when I clicked debug when I came in. I even left my computer on with VS running overnight (which I almost never do, and I have restarted since) so I could it and all my internet tabs as I left them. The computer was locked, so unless some very resourceful individual decided to mess with me, nothing changed overnight.

I'm using websocket-sharp, and when I connect to the websocket (which does seem to happen successfully), the OnOpen event isn't raised.

The bit where websocket-sharp raises the event is in the following lines.

private void open ()
{
  _inMessage = true;
  startReceiving ();
  try {
    OnOpen.Emit (this, EventArgs.Empty);
  }
  catch (Exception ex) {
    _logger.Error (ex.ToString ());
    error ("An error has occurred during the OnOpen event.", ex);
  }

It reaches the OnOpen.Emit, and doesn't throw the exception, so it seems to think it's raising the event. Event is seen below

public event EventHandler OnOpen;

It does not seem to reach this line as when I put a breakpoint there it isn't paused. I've never used the .Emit way of raising events before, and not finding much in research, so maybe somethings is going wrong there?

My code is below.

public Form1()
    {
        InitializeComponent();
        this.Shown += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, EventArgs e)
    {

        using (var ws = new WebSocket("ws://169.254.101.183"))
        {
            ws.OnMessage += (sender2, e2) =>
                textBox1.Text = e2.Data.ToString();

            ws.Connect();
            ws.OnOpen += (sender2,e2) =>
                textBox1.Text = "connected";

            /*ws.OnError += (sender2, e2) =>
                textBox1.Text = e2.Message;*/

            //textBox1.Text = ".";
        }
    }

Is there any obvious reason that OnOpen.Emit should not actually raise the OnOpen event?

H.Ramsey
  • 43
  • 1
  • 10

2 Answers2

1

In the MainWindow_Loaded method are you calling Connect before you subscribe to the OnOpen event.

If you subscribe to the event before calling Connect then the textBox1.Text should be set to "connected" after a successful connection.

CHMaagaard
  • 76
  • 4
1

In your case the real reason is this line

 using (var ws = new WebSocket("ws://169.254.101.183"))

When your block ends 'ws' object becomes disposed including your event handler. After some delay you have response from WebSocket, but handler already destroyed.

Mortaly
  • 28
  • 5