gpt4 book ai didi

websocket - 如何使用 websocket-sharp 创建客户端?

转载 作者:行者123 更新时间:2023-12-01 06:04:35 24 4
gpt4 key购买 nike

我正在使用 ClientWebSocket 订阅 REST 服务,但希望能够改用 websocket-sharp。

static async void MonitorISY(string IPAddress, string userName, string password, IMessageWriter writer)
{
ClientWebSocket client = new ClientWebSocket();
client.Options.AddSubProtocol("ISYSUB");
client.Options.SetRequestHeader("Origin", "com.universal-devices.websockets.isy");
var auth = Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password));
client.Options.SetRequestHeader("Authorization", "Basic " + auth);
await client.ConnectAsync(new Uri("ws://" + IPAddress + "/rest/subscribe"), CancellationToken.None);

var receiveBufferSize = 512;
byte[] buffer = new byte[receiveBufferSize];

writer.Clear();

while (true)
{
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var resultJson = (new UTF8Encoding()).GetString(buffer);
writer.WriteLn(resultJson);
writer.WriteLn();
}
}

这是我的 websocket-sharp 尝试。当 ws.Connect(); 被调用,我收到 Not a WebSocket 握手响应错误消息。在工作代码中,我必须设置 Origin、SubProtocol 和 RequestHeader。我想我对 websocket-sharp 代码做的是正确的,除了请求头。我一直无法找到指定身份验证的工作示例。
        using (var nf = new Notifier())
using (var ws = new WebSocket("ws://172.16.0.40/rest/subscribe", "ISYSUB"))
{
ws.Log.Level = LogLevel.Trace;

var username = "user";
var password = "pass";
ws.Origin = "com.universal-devices.websockets.isy";
ws.SetCredentials(username, password, true);

ws.OnOpen += (sender, e) => ws.Send("Hi, there!");

ws.OnMessage += (sender, e) =>
nf.Notify(
new NotificationMessage
{
Summary = "WebSocket Message",
Body = !e.IsPing ? e.Data : "Received a ping.",
Icon = "notification-message-im"
}
);

ws.OnError += (sender, e) =>
nf.Notify(
new NotificationMessage
{
Summary = "WebSocket Error",
Body = e.Message,
Icon = "notification-message-im"
}
);

ws.OnClose += (sender, e) =>
nf.Notify(
new NotificationMessage
{
Summary = String.Format("WebSocket Close ({0})", e.Code),
Body = e.Reason,
Icon = "notification-message-im"
}
);

ws.Connect();

最佳答案

我认为最好的例子是 https://github.com/sta/websocket-sharp/tree/master/Example3

虽然我确实需要做一些微小的调整才能让它在 Visual Studio 2017 Enterprise 中编译。

index.html 基于 http://www.websocket.org/echo.html

关于websocket - 如何使用 websocket-sharp 创建客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com