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

时间:2017-01-14 13:42:41

标签: websocket websocket-sharp clientwebsocket

我使用 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 WebSocket握手响应错误消息。在工作代码中,我必须设置Origin,SubProtocol和RequestHeader。我认为我正在为websocket-sharp代码正确地做这件事,但Request Header除外。我一直无法找到指定身份验证的工作示例。

        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();

1 个答案:

答案 0 :(得分:0)

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

尽管我确实必须进行一些小的调整才能使其在Visual Studio 2017 Enterprise中进行编译。

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