c# - 如何将数据从类文件传递到剃须刀页面?
问题描述
我正在尝试使用 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");
}
解决方案
推荐阅读
- mysql - 从 MS Access 检索 MySQL 数据库中最后插入行的自动编号值始终返回 0
- swift - SpriteKit中单个节点的自定义重力
- c# - 如何在 ASP.NET Core 3.1 中将密码存储到我的邮件功能
- ios - 无法解析临时密钥,如何发送未修改的 JSON
- sql - 如何组合只有几个相似列的两个表?
- amazon-web-services - 如何存储数值 EC2 计算结果 - 在 AWS S3 存储桶中序列化 Julia 对象和 Julia DataFrame?
- javascript - 为什么文件扩展名很重要:XML Parsing Error: not well-formed for plain text file
- javascript - 在 VSCode 中调试时,如何在程序结束之前查看环境?
- linux - 使用 DWARF 版本 4 查找框架基础和变量位置
- sparql - 从 rdflib.term.URIRef 和 rdflib.term.Literal 中提取值