首页 > 解决方案 > 如何将数据从类文件传递到剃须刀页面?

问题描述

我正在尝试使用 blazor 服务器制作带有 Web UI 的服务器程序。但我无法找到将数据从我的服务器类传递到我的索引文件的方法。在这个项目中,我有两个主要问题。

1 - 当客户端连接到服务器并将其对象存储在字典中时,UI 不会刷新。

2 - 我不知道如何将错误消息从我的服务器类传递到剃刀文件(索引)。

即使我试图直接从我的服务器类制作这些东西,我也想从一个中间件类制作它们,该类将从服务器类接收数据然后传递给我的索引文件。

我想做的是:

索引剃刀

@page "/"
@using System.Net.Sockets
@using System.Threading
@inject Server server

<table class="table">
  <thead>
        <tr>
            <th scope="col">Dispositivos</th>
            <th scope="col">IP</th>
            <th scope="col">Porta</th>
        </tr>
  </thead>
  <tbody>
        <tr>
            <td>Servidor</td>
            <td>127.0.0.1</td>
            <td>8600</td>
        </tr>
        @* Remove this and get data from my middleware class *@
        @foreach (KeyValuePair<string, TcpClient> client in server._connectedClients)
        {
            string endpoint = client.Value.Client.RemoteEndPoint.ToString();
            string ip = endpoint.Split(":")[0];
            string port = endpoint.Split(":")[1];
            string device = client.Key;

            <tr>
                <td>@device</td>
                <td>@ip</td>
                <td>@port</td>
            </tr>
        }
  </tbody>
</table>

@code {
    protected override void OnInitialized() {
        Thread serverThread = new Thread(() => server.Start());
        serverThread.Start();
    }
}

中间件类

class Middleware {
    public string[] AddDeviceEntry(string device, string endpoint) {
       // Return this object to index.razor somehow and update the UI
       return new string[] { device, endpoint }; 
    }

    public string ErrorMessage(string msg) {
        // Return this object to index.razor somehow and update the UI
        return msg;
    }
}

服务器.cs

class Server {
    private TcpListener _server;
    private Middleware _mid;
    public Dictionary<string, TcpClient> _connectedClients = new();

    public Server(int portNum, Middleware middleware) {
        _server = new TcpListener(IPAddress.Any, portNum);
        _mid = middleware;
    }

    // Some stuffs...

    // When client connects
    _connectedClients.Add("some device", client);
    _mid.AddDeviceEntry("some device", client.Client.RemoteEndPoint.ToString());

    // When getting some error
    _mid.ErrorMessage("some error message");
}

标签: c#blazor-server-side

解决方案


推荐阅读