1

我需要在 c# 中为特定的 url(不能显示)创建一个 websocket。是否有类似于 Java 中的 WebSocket API 或 C# 中的 libwebsockets 的东西?

我已经按照一些 SO 答案尝试使用 WebSocketSharp 和 ChilKat。还尝试使用 Microsoft 的 WebSocket 命名空间。但总是收到“未授权”错误 401。我还尝试执行 Http 获取并尝试添加标头以按照教程在 MDN 文档中创建 WebSocket 服务器来将套接字升级到 Websocket,但只得到一个重定向的网页作为回报。这是我用于 HTTP 升级请求的代码。我是 C# 的初学者。

ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                    | SecurityProtocolType.Tls11
                                                    | SecurityProtocolType.Tls12
                                                    | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
            {
                return true;
            };
            var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
            http.AllowAutoRedirect = false;
            http.UseDefaultCredentials = true;
            http.PreAuthenticate = true;
            http.Credentials = CredentialCache.DefaultCredentials;
            http.Proxy.Credentials = CredentialCache.DefaultCredentials;
            http.Accept = "application/json";
            http.ContentType = "application/json";
            http.Method = "GET";
            http.Connection = "Open";
            http.Headers.Add("Authorization", "Bearer " + Token);
            //http.Headers.Add("Connection", "Upgrade");
            http.Headers.Add("Upgrade", "websocket");
            http.KeepAlive = true;

我想要实现的是,

Websocket socket = new Websocket();
socket.addHeader(Authorization, Bearer, Token);
socket.connect(); 

提前感谢您的任何意见。

4

1 回答 1

0

我正在使用ClientWebSocket使用 OAuth 令牌连接到 Zendesk 聊天流 API,如下所示:

var webSocket = new ClientWebSocket();
webSocket.Options.SetRequestHeader("Authorization", $"Bearer {_oauthToken}");
var cts = new CancellationTokenSource();
await webSocket.ConnectAsync(new Uri(url), cts.Token);

这个对我有用!

于 2021-11-16T17:55:30.127 回答