Search code examples
asp.net-core.net-coreblazorblazor-client-side

How can I use Socket in Blazor Client-side?


I wanna try to connect to a machine by Blazor Client-side.

I installed the Nuget package System.Net.Sockets to achieve it.

Here is the code:

@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);
            }
        }
    }   
}

When the breakpoint runs at

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

It reports an error only with this: enter image description here


Solution

  • You won't be able to do this.

    This is a Browser / JavaScript security feature, sockets are not allowed.

    You will have to use WebSockets (SignalR) or the HttpClient. HttpClient has been re-implemented in Blazor to go through JavaScript.

    When you need to access an existing service with sockets you will need a server back-end to do that. Consider Blazor/Server or Blazor/Wasm Hosted.