我有以下情况:
1.I am opening a socket to a server from which i will start receiving data
2.I am launching a http request (to the same server) which will return a result
套接字将在httprequest的整个生命周期中保持打开状态。
为了对套接字部分执行此操作,我使用了javascript interop。我正在调用静态.NET
方法(用Invokable) .On this method i am firing an event which is handled by my
blazor组件修饰。
我不明白为什么我没有按顺序从js中获取消息:
js
window.open={
open: function (url) {
socket = new WebSocket(url);
socket.onopen = function () {
console.log("opened socket");
}
socket.reject = function () {
console.log("rejected");
}
socket.onmessage = function (evt) {
DotNet.invokeMethodAsync("BenchUI", "CB_OnMessage", evt.data);
}
}
}
互操作
public class InteropService
{
protected IJSRuntime runtime;
public InteropService(IJSRuntime runtime)
{
this.runtime = runtime;
}
public async Task OpenSocketAsync()
{
await runtime.InvokeAsync<string>("methods.open", "ws://localhost:8500/monitor");
}
public async Task CloseSocketAsync()
{
await runtime.InvokeAsync<string>("methods.close");
}
}
}
组件
private delegate void OnSocketMessage(string data);
private static event OnSocketMessage socketEvent;
[JSInvokable("CB_OnMessage")]
public static void SocketCB(string data)
{
Console.WriteLine("From js received message");
socketEvent?.Invoke(data);
}
protected async override Task OnInitAsync()
{
socketEvent += async (x) =>
{
await DispatchAsync(x);
this.StateHasChanged();
};
this.interopService = new InteropService(this.runtime);
}
protected async Task DispatchAsync(MonitorMessage message)
{
try
{
switch (message)
{
case "a' :
break;
case "b":
break;
case "c":
break;
default:throw new NotSupportedException();
}
}
this.StateHasChanged();
}
PS
由于在服务器上,我总是按顺序发送消息:首先是"a"
,然后是"b"
,有时我会收到什么消息我的b
方法中的a
之前的Dispatch
吗?
这仅在blazor级别发生,因为在js部分中,我按顺序接收所有消息。