如何使用WebSocket4Net库代理

时间:2014-04-11 23:20:09

标签: c# .net websocket websocket4net

我正在使用C#和WebSocket4Net库构建安全的WebSockets客户端。我想通过标准代理代理我的所有连接。

这个lib使用SuperSocket.ClientEngine.Common.IProxyConnector来指定websocket连接的代理,但我不确定我应该如何实现它。

有没有人使用过此库并可以提供一些建议?

1 个答案:

答案 0 :(得分:14)

我必须这样做,通过Fiddler推送所有websocket连接,以便于调试。由于WebSocket4Net作者选择重用他的IProxyConnector界面,System.Net.WebProxy不能直接使用。

this link上,作者建议使用他的父库SuperSocket.ClientEngine中的实现,您可以从CodePlex下载并包含SuperSocket.ClientEngine.Common.dllSuperSocket.ClientEngine.Proxy.dll我不建议这样做。这会导致编译问题,因为他(很差)选择在ClientEngineWebSocket4Net中使用相同的命名空间,同时在dll'中定义了IProxyConnector。第


什么对我有用:

为了让它通过Fiddler进行调试,我将这两个类复制到我的解决方案中,并将它们更改为本地命名空间:

HttpConnectProxy似乎在以下行中有一个错误:

if (e.UserToken is DnsEndPoint)

更改为:

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


在那之后,事情很好。示例代码:

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!");
}