SteveSandersonMS / dotnet-wasi-sdk

Packages for building .NET projects as standalone WASI-compliant modules
518 stars 35 forks source link

Simple WebSocket Client Failed #35

Open d3c0d3d opened 2 years ago

d3c0d3d commented 2 years ago

This simple code using echo simple in websocket fails, does anyone have any ideas?

WasiApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Wasi.Sdk" Version="0.1.2-preview.10061" />
  </ItemGroup>

</Project>

Program.cs

using System.Runtime.InteropServices;
using System.Net.WebSockets;

Console.WriteLine($"Running in {RuntimeInformation.OSArchitecture}");

CancellationTokenSource source = new CancellationTokenSource();
using (var ws = new ClientWebSocket())
{
    await ws.ConnectAsync(new Uri("wss://demo.piesocket.com/v3/channel_1?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV&notify_self"), CancellationToken.None);
    byte[] buffer = new byte[256];
    while (ws.State == WebSocketState.Open)
    {
        var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        if (result.MessageType == WebSocketMessageType.Close)
        {
            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
        }
        else
        {
            HandleMessage(buffer, result.Count);
        }
    }
}

static void HandleMessage(byte[] buffer, int count)
{
    Console.WriteLine($"Received {BitConverter.ToString(buffer, 0, count)}");
}

It runs but then fails

image