How to use proxies with the WebSocket4Net library

2020-06-12 05:15发布

问题:

I'm building a secure WebSockets client using C# and the WebSocket4Net library. I would like for all my connections to be proxied through a standard proxy.

This lib uses the SuperSocket.ClientEngine.Common.IProxyConnector to specify a websocket connection's proxy, but I'm not sure how I'm supposed to implement that.

Has anyone worked with this library and can offer some advice?

回答1:

I had to do the same, to push all websocket connections through Fiddler, for easier debugging. Because the WebSocket4Net author chose to re-use his IProxyConnector interface, System.Net.WebProxy is not directly useable.

On this link the author suggests using the implementations from his parent library SuperSocket.ClientEngine which you can download from CodePlex and include both the SuperSocket.ClientEngine.Common.dll and SuperSocket.ClientEngine.Proxy.dll. I do not recommend this. This causes compiling issues because he (poorly) chose to use the same namespace with both ClientEngine and WebSocket4Net with IProxyConnector defined in both dll's.


What worked for me:

To get it working for debugging through Fiddler, I copied these two classes into my solution, and changed them to the local namespace:

  • HttpConnectProxy.cs
  • ProxyConnectionBase

HttpConnectProxy seemed to have a bug on the following line:

if (e.UserToken is DnsEndPoint)

change to:

if (e.UserToken is DnsEndPoint || targetEndPoint is DnsEndPoint)


After that, things worked fine. Sample code:

private WebSocket _socket;

public Initialize()
{
    // initialize the client connection
    _socket = new WebSocket("ws://echo.websocket.org", origin: "http://example.com");

    // go through proxy for testing
    var proxy = new HttpConnectProxy(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
    _socket.Proxy = (SuperSocket.ClientEngine.IProxyConnector)proxy;

    // hook in all the event handling
    _socket.Opened += new EventHandler(OnSocketOpened);
    //_socket.Error += new EventHandler<ErrorEventArgs>(OnSocketError);
    //_socket.Closed += new EventHandler(OnSocketClosed);
    //_socket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(OnSocketMessageReceived);

    // open the connection if the url is defined
    if (!String.IsNullOrWhiteSpace(url))
        _socket.Open();
}

private void OnSocketOpened(object sender, EventArgs e)
{
    // send the message
    _socket.Send("Hello World!");
}