-1

This is my first post on Stack Overflow, so please excuse me if my question isn't very clear. To add more context, I want to open a connection to a WebSocket when the connect button is clicked and for a message to be sent from the connection opened by the connect button when the sent button is clicked. The problem is that I can not access the ws variable that I have created in the connect button from the send message button. The code below may give you more of an idea of what I want to do:

   private void buttonConnect_Click(object sender, EventArgs e)
   {
        var ws = new WebSocket(textBoxSocketUrl.Text);

        ws.Connect();
   }

   private void buttonSendMessage_Click(object sender, EventArgs e)
   {
       ws.Send(textBoxMessage.Text);
   }

Thanks.

1 Answers1

0

This is expected, that you can not see ws variable, because it was created in another "context". In order to get it, ws should be part of your class. Try to change your code to something like this:

private WebSocket ws;

private void buttonConnect_Click(object sender, EventArgs e)
   {
        ws = new WebSocket(textBoxSocketUrl.Text);

        ws.Connect();
   }

   private void buttonSendMessage_Click(object sender, EventArgs e)
   {
       ws.Send(textBoxMessage.Text);
   }
Anna Melashkina
  • 422
  • 2
  • 13