Skip to content

Lupusa87/BlazorWebSocketHelper

Repository files navigation

Blazor WebSocket Helper

If you like my blazor works and want to see more open sourced repos please support me with paypal donation

Please send email if you consider to hire me.

!!!!!!!!!!!! Readme should be updated because it is relevant to version 1.0.1 !!!!!!!!!!!!

This repo contains Pure WebSocket library for blazor.

Helper is available on nuget

For install use command - Install-Package BlazorWebSocketHelper

After installing package please add bellow script to your index.html

<script src="_content/BlazorWebSocketHelper/BwsJsInterop.js"></script>

You can use websocket in blazor easy and convenient way using this library.

image

Usage sample:

markup:

<div style="margin:5px">
    <button class="btn btn-primary" style="width:120px;margin:5px" onclick="@WsConnect">@Ws_Button</button>
    <span style="margin:5px">URL</span>
    <input bind="@Ws_URL" style="margin:5px;width:250px" />
    <span style="width:120px;margin:5px">status:@Ws_Status</span>
    <button class="btn btn-primary" style="margin:5px" onclick="@WsGetStatus">Get status</button>
</div>
<br />
<div style="margin:5px">
    <input style="margin:5px;width:250px" bind="@Ws_Message" />
    <button class="btn btn-primary" style="margin:5px" onclick="@WsSendMessage">Send</button>
</div>
<br />
<span style="margin:5px">Log:</span>
<br />
@foreach (var item in WebSocketHelper1.Log)
{
    <br />
    <CompMessage bwsMessage="@item" parent="@this" />
    <br />

}

code:

  public string Ws_URL = "wss://echo.websocket.org";
  protected WebSocketHelper WebSocketHelper1;
  
  public void WsConnect()
  {
    WebSocketHelper1 = new WebSocketHelper(Ws_URL);

    WebSocketHelper1.OnStateChange = WsOnStateChange;
    WebSocketHelper1.OnMessage = WsOnMessage;
    WebSocketHelper1.OnError = WsOnError;
  }
  public void WsOnStateChange(short par_state)
  {
    Ws_Status = WebSocketHelper1.bwsState.ToString();
    StateHasChanged();
  }
  public void WsOnError(string par_error)
  {
    BwsJsInterop.Alert(par_error);
  }
  public void WsOnMessage(string par_message)
  {
    StateHasChanged();
  }
  public void WsSendMessage()
  {
      if (WebSocketHelper1.bwsState == BwsEnums.BwsState.Open)
      {
          if (!string.IsNullOrEmpty(Ws_Message))
          {
              WebSocketHelper1.send(Ws_Message);
              Ws_Message = string.Empty;
              StateHasChanged();
          }
          else
          {
              BwsJsInterop.Alert("Please input message");
          }
      }
      else
      {
          BwsJsInterop.Alert("Connection is closed");
      }
  }
  

For example this helper was used here

You can see code here

Any PRs are welcome.

Releases

No releases published

Packages

No packages published