websocket-sharp icon indicating copy to clipboard operation
websocket-sharp copied to clipboard

Could be possible to allow Regular expressions for path in Service add method?

Open GibbOne opened this issue 9 years ago • 2 comments

In WebSocketServer, could be useful to have a method AddWebSocketService with path argument as a regular expression.

In this way a set of request url could be managed by the same WebSocketBehavior.

Something like what Owin.Websocket does in the following code.

using Owin.WebSocket.Extensions;

//For dynamic routes where you may want to capture the URI arguments use a Regex route
app.MapWebSocketPattern<MyWebSocket>("/captures/(?<capture1>.+)/(?<capture2>.+)");

What do you think about this?

GibbOne avatar Apr 02 '16 09:04 GibbOne

I tested in my project a simple modification of InternalTryGetServiceHost function in WebSocketServiceManager.cs.

using System.Linq;
using System.Text.RegularExpressions;
    internal bool InternalTryGetServiceHost (string path, out WebSocketServiceHost host)
    {
      bool ret;
      lock (_sync) {
        path = HttpUtility.UrlDecode (path).TrimEndSlash ();

        var results = from result in _hosts
                        where Regex.Match(path, result.Key, RegexOptions.Singleline).Success
                        select result;
        ret = results.Count() != 0;
        host = results.FirstOrDefault().Value;
      }

      if (!ret)
        _logger.Error (
          "A WebSocket service with the specified path isn't found:\n  path: " + path);

      return ret;
    }

It works. For sure it can increase connection time but could be done on a new method (like AddWebSocketServiceWithPattern) rather than AddWebSocketService.

GibbOne avatar Apr 02 '16 18:04 GibbOne

Code that can work directly in Server/WebSocketServiceManager.cs (a little modification):

        //internal bool InternalTryGetServiceHost (
        //  string path,
        //  out WebSocketServiceHost host
        //)
        //{
        //  path = path.TrimSlashFromEnd ();

        //  lock (_sync)
        //    return _hosts.TryGetValue (path, out host);
        //}

        internal bool InternalTryGetServiceHost(string path, out WebSocketServiceHost host)
        {
            bool ret;
            lock (_sync)
            {
                path = HttpUtility.UrlDecode(path).TrimEnd('/');

                var results = from result in _hosts
                              where Regex.Match(path, result.Key, RegexOptions.Singleline).Success
                              select result;
                ret = results.Count() != 0;
                host = results.FirstOrDefault().Value;

                return ret;
            }
        }

1234567Yang avatar Apr 20 '25 23:04 1234567Yang