如何在 Blazor 客户端使用 Socket?

How can I use Socket in Blazor Client-side?

我想尝试通过 Blazor 客户端连接到一台机器。

我安装了Nuget包System.Net.Sockets来实现它。

代码如下:

@page "/fetchdata"
@inject HttpClient Http
@using System.Net.Sockets;
@using System.Net;

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>



@code {    
    Socket S; 
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            IPAddress ipAddress = IPAddress.Parse("192.168.200.111");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 23);
            try
            {
                S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                S.Connect(ipEndPoint);

                Byte[] inBuffer = new Byte[1024];
                S.Send(System.Text.Encoding.Default.GetBytes("PEY" + Environment.NewLine));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }   
}

当断点运行在

S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

它仅报告错误:

您将无法执行此操作。

这是浏览器/JavaScript 安全功能,不允许套接字。

您将不得不使用 WebSockets (SignalR) 或 HttpClient。 HttpClient 已在 Blazor 中重新实现以通过 JavaScript。

当您需要使用套接字访问现有服务时,您将需要一个服务器后端来执行此操作。考虑 Blazor/Server 或 Blazor/Wasm 托管。