sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.75k stars 1.66k forks source link

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

Open GibbOne opened 8 years ago

GibbOne commented 8 years ago

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 commented 8 years ago

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.