.Net Core – Binance.Net 从数据模型 websockets 实时更新视图
.Net Core – Binance.Net update view in real time from data model websockets
我有一个 .Net Core 应用程序,我正在使用 Binance.Net API。我想实时显示交易并用当前交易更新我的视图。我不确定这样做的正确方法。可能 ajax?传入的数据全部是 c#,因此在我无法使用 javascript websockets 更新 UI 的地方变得更加困难。除非有办法解决这个问题。
我有一个视图,还有一个带有列表框的局部视图。目前,当 websocket 数据进来时,我将其添加到模型中,如果我单击部分中的按钮,列表框会显示最近的交易。所以我部分在那里。
public async Task<IActionResult> Index()
{
_logger.LogInformation("Start Capture");
//var price = await _marketFeed.StartBTCCapture();
//var incomingBTC = await _binanceSocketClient.SubscribeToTradeUpdatesAsync("BTCUSD", (data) =>
//{
// //(data);
// // _logger.LogInformation(data.Price.ToString());
// Console.WriteLine(data.Price);
//});
List<TradeResult> trades = new List<TradeResult>();
await GetPartial(trades);
//_logger.LogInformation(price.Data);
//var conn = new WebSocket();
//HttpListener httpListener = new HttpListener();
//httpListener.Prefixes.Add("ws://localhost:50021/StartBTCCapture");
//httpListener.Start();
//var buffer = new byte[1024 * 4];
//HttpListenerContext context = await httpListener.GetContextAsync();
//if (context.Request.IsWebSocketRequest)
//{
// HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
// WebSocket webSocket = webSocketContext.WebSocket;
// while (webSocket.State == WebSocketState.Open)
// {
// await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// }
//}
return View();
}
public async Task<IActionResult> GetPartial(List<TradeResult> trades)
{
var incomingBTC = await _binanceSocketClient.SubscribeToTradeUpdatesAsync("BTCUSD", (data) =>
{
//(data);
// _logger.LogInformation(data.Price.ToString());
Console.WriteLine(data.Price);
trades.Add(new TradeResult
{
Price = data.Price
});
});
return PartialView("BoxView", trades);
}
//Partial
<div class="container">
<form>
<table>
<tr>
<th>Price</th>
</tr>
@foreach(var obj in Model)
{
<tr>
<td>
@obj.Price.ToString()
</td>
</tr>
}
</table>
<input type="submit" value="btn" />
</form>
</div>
所以我最终解决了这个问题。
我最终将 IMemoryCache 添加到我的 .Net Core Web 应用程序。
然后我使用 PartialView 在我的视图上显示缓存。
我使用 jquery .load 函数来实时显示缓存。
// PartialView
@model TestVM
<select class="form-control" id="testBox" size="5" style="width:510px;" asp-for="TradeID"
asp-items="@(new SelectList(ViewBag.Cache ?? string.Empty, "TradeID", "Price"))">
</select>
//Main View
<div id="divadd col-6">
<partial name="ShowCache.cshtml" />
</div>
@section Scripts {
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
<script>
function addData(data) {
if (data != null) {
var element = document.getElementById("lstBox")
var opt = document.createElement("option");
opt.text = data.s + "\t\t" + data.p + " " + data.q ;
opt.value = data;
element.options.add(opt);
$.ajax({
url: '@Url.Action("AddDataToMemory", "Home")',
type: 'GET',
//contentType: 'text/plain',
data: { model: JSON.stringify(data) },
//contentType: "application/json",
//dataType: "json",
dataType: "json",
traditional: true,
//data: { model: data },
//data: data ,
//contentType: type of data your sending
//dataType: what you're expecting back from the server: json, html, text, etc
//dataType: 'JSON',
//'application/x-www-form-urlencoded',
})
.done(function (e) {
@*$.ajax({
url: '@Url.Action("ShowCache", "Home")',
type: 'GET',
})*@
$('#testBox').load('@Url.Action("ShowCache", "Home")');
//alert('done');
})
return false;
}
}
}
//Controller
public IActionResult ShowCache()
{
if (_memoryCache.TryGetValue<List<string>>("Data", out List<string> cache))
{
List<TestVM> lstTest = new List<TestVM>();
foreach (string model in cache)
{
if (!string.IsNullOrWhiteSpace(model))
{
var jsonDoc = JsonDocument.Parse(model);
var price = jsonDoc.RootElement.GetProperty("p");
var id = jsonDoc.RootElement.GetProperty("t");
var symbol = jsonDoc.RootElement.GetProperty("s");
TestVM testVM = new TestVM
{
Price = Convert.ToDecimal(price.ToString()),
TradeID = Convert.ToInt64(id.ToString()),
Symbol = symbol.ToString()
};
lstTest.Add(testVM);
}
}
//ViewBag.Cache = cache;
ViewBag.Cache = lstTest;
}
return PartialView();
}
我有一个 .Net Core 应用程序,我正在使用 Binance.Net API。我想实时显示交易并用当前交易更新我的视图。我不确定这样做的正确方法。可能 ajax?传入的数据全部是 c#,因此在我无法使用 javascript websockets 更新 UI 的地方变得更加困难。除非有办法解决这个问题。 我有一个视图,还有一个带有列表框的局部视图。目前,当 websocket 数据进来时,我将其添加到模型中,如果我单击部分中的按钮,列表框会显示最近的交易。所以我部分在那里。
public async Task<IActionResult> Index()
{
_logger.LogInformation("Start Capture");
//var price = await _marketFeed.StartBTCCapture();
//var incomingBTC = await _binanceSocketClient.SubscribeToTradeUpdatesAsync("BTCUSD", (data) =>
//{
// //(data);
// // _logger.LogInformation(data.Price.ToString());
// Console.WriteLine(data.Price);
//});
List<TradeResult> trades = new List<TradeResult>();
await GetPartial(trades);
//_logger.LogInformation(price.Data);
//var conn = new WebSocket();
//HttpListener httpListener = new HttpListener();
//httpListener.Prefixes.Add("ws://localhost:50021/StartBTCCapture");
//httpListener.Start();
//var buffer = new byte[1024 * 4];
//HttpListenerContext context = await httpListener.GetContextAsync();
//if (context.Request.IsWebSocketRequest)
//{
// HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
// WebSocket webSocket = webSocketContext.WebSocket;
// while (webSocket.State == WebSocketState.Open)
// {
// await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// }
//}
return View();
}
public async Task<IActionResult> GetPartial(List<TradeResult> trades)
{
var incomingBTC = await _binanceSocketClient.SubscribeToTradeUpdatesAsync("BTCUSD", (data) =>
{
//(data);
// _logger.LogInformation(data.Price.ToString());
Console.WriteLine(data.Price);
trades.Add(new TradeResult
{
Price = data.Price
});
});
return PartialView("BoxView", trades);
}
//Partial
<div class="container">
<form>
<table>
<tr>
<th>Price</th>
</tr>
@foreach(var obj in Model)
{
<tr>
<td>
@obj.Price.ToString()
</td>
</tr>
}
</table>
<input type="submit" value="btn" />
</form>
</div>
所以我最终解决了这个问题。
我最终将 IMemoryCache 添加到我的 .Net Core Web 应用程序。 然后我使用 PartialView 在我的视图上显示缓存。 我使用 jquery .load 函数来实时显示缓存。
// PartialView
@model TestVM
<select class="form-control" id="testBox" size="5" style="width:510px;" asp-for="TradeID"
asp-items="@(new SelectList(ViewBag.Cache ?? string.Empty, "TradeID", "Price"))">
</select>
//Main View
<div id="divadd col-6">
<partial name="ShowCache.cshtml" />
</div>
@section Scripts {
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
<script>
function addData(data) {
if (data != null) {
var element = document.getElementById("lstBox")
var opt = document.createElement("option");
opt.text = data.s + "\t\t" + data.p + " " + data.q ;
opt.value = data;
element.options.add(opt);
$.ajax({
url: '@Url.Action("AddDataToMemory", "Home")',
type: 'GET',
//contentType: 'text/plain',
data: { model: JSON.stringify(data) },
//contentType: "application/json",
//dataType: "json",
dataType: "json",
traditional: true,
//data: { model: data },
//data: data ,
//contentType: type of data your sending
//dataType: what you're expecting back from the server: json, html, text, etc
//dataType: 'JSON',
//'application/x-www-form-urlencoded',
})
.done(function (e) {
@*$.ajax({
url: '@Url.Action("ShowCache", "Home")',
type: 'GET',
})*@
$('#testBox').load('@Url.Action("ShowCache", "Home")');
//alert('done');
})
return false;
}
}
}
//Controller
public IActionResult ShowCache()
{
if (_memoryCache.TryGetValue<List<string>>("Data", out List<string> cache))
{
List<TestVM> lstTest = new List<TestVM>();
foreach (string model in cache)
{
if (!string.IsNullOrWhiteSpace(model))
{
var jsonDoc = JsonDocument.Parse(model);
var price = jsonDoc.RootElement.GetProperty("p");
var id = jsonDoc.RootElement.GetProperty("t");
var symbol = jsonDoc.RootElement.GetProperty("s");
TestVM testVM = new TestVM
{
Price = Convert.ToDecimal(price.ToString()),
TradeID = Convert.ToInt64(id.ToString()),
Symbol = symbol.ToString()
};
lstTest.Add(testVM);
}
}
//ViewBag.Cache = cache;
ViewBag.Cache = lstTest;
}
return PartialView();
}