'Open a websocket connection with a parameter

When opening a websocket connection (in JavaScript) to my custom server I wrote (C#), I want to include a parameter at the end of the URL for example 'ws://127.0.0.1:9003/myParameter'.

        var socket = new WebSocket('ws://127.0.0.1:9003?myParameter=1');

        socket.onopen = function () {
            deferred.resolve(true);
            socket.close();
        };

On the server side I have this method accepting connections:

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                t.Start();
                while (true)
                {
                    TcpClient c = t.AcceptTcpClient();
                    WebSocketClient w = new WebSocketClient(c);
                    webSocketClientManager.AddClient(w);
                }                   
            }
            catch (Exception ex)
            {
                // log error
            }
        }
    }

I have no issues establishing the connection. What I would like is to somehow read/see if 'myParameter' exists in the URL as it is trying to connect.

TIA



Solution 1:[1]

var ws = new WebSocket ("ws://example.com/?name=nobita");
ws.SetCookie (new Cookie ("name", "nobita"));

public class Chat : WebSocketBehavior
{
  private string _name;
  ...

  protected override void OnOpen ()
  {
    _name = Context.QueryString["name"];
  }

  ...
}

Alternatively, you could send the parameters you wanr as a message from the client after connection is complete, then in onMessage you could capture the message and deal with it as you wish.

WebSocket Client:

public static void Main (string[] args)
    {
      using (var ws = new WebSocket ("ws://..../Laputa")) {
        ws.OnMessage += (sender, e) =>
            Console.WriteLine ("Parm: " + e.Data);

        ws.Connect ();
        ws.Send ("Parameters");
        Console.ReadKey (true);
      }
    }

Server:

 public class Laputa : WebSocketBehavior
  {
    protected override void OnMessage (MessageEventArgs e)
    {
      var msg = e.Data == ;

      Send (msg);
    }
  }

  public class Program
  {
    public static void Main (string[] args)
    {
      var wssv = new WebSocketServer ("ws://..../Laputa");

      wssv.AddWebSocketService<Laputa> ("/Laputa");
      wssv.Start ();
      Console.ReadKey (true);
      wssv.Stop ();
    }
  }

Check for more details

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1