asp.net-core - 如何在 Blazor 客户端使用 Socket?

标签 asp.net-core .net-core blazor 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);

它只报告错误: enter image description here

最佳答案

您将无法执行此操作。

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

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

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

关于asp.net-core - 如何在 Blazor 客户端使用 Socket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61906292/

相关文章:

blazor - 检索子组件中的 Blazor 页面路由参数

c# - 如何从一批新插入的数据中获取自动生成的 ID?

c# .Net Core 3.1 Azure App Service Windows - 应用程序无法检索应用程序设置

c# - 从 docker 容器连接到 SQL Server 数据库

html - 如何默认检查 Blazor 中的 InputRadio 单选按钮

c# - 如何向 inputRadio 添加 on change 事件?

asp.net - 当前的 .NET SDK 不支持面向 .NET Core 2.1

asp.net-web-api - ASP.NET 核心 Web API : Why need ModelState validation in Get request?

c# - 如何从命令行发布 .Net Core ASP 便携版?

visual-studio - Visual Studio 无法创建 docker 图像