我在 Mono、Linux、ARM 上的 WebSockets 遇到问题(它是一个 Jetson Nano,以防万一)。
此示例连接到 WebSocket 服务器,然后等待返回的第一条文本消息,将其记录下来,仅此而已。该程序在 Windows 下可以正常运行。但是当我在 Nano(ARM Linux Ubuntu、Mono、Framework v4.6.1)上运行它时,它永远不会收到消息。它连接并发出 ReceiveAsync,但 ReceiveAsync 永远不会完成。
我的测试 WebSocket 服务器在连接后立即返回一条“hello”文本消息,并且服务器正常工作,因为其他客户端可以正确连接并接收 hello 消息。只是这个 C# Mono 构建不起作用。
它使用 wss(基于 HTTPS 的 WebSockets),并且服务器在开发过程中恰好是自签名证书,因此 ServerCertificateValidationCallback 返回 true 以允许它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClientTest
{
class Program
{
static ManualResetEvent exitEvent = null;
static void HandleMessage(System.Net.WebSockets.WebSocketMessageType type, byte[] buffer, int count)
{
Console.WriteLine(string.Format("Received {0} message of {1} bytes", type.ToString(), count));
if (type == WebSocketMessageType.Text)
{
string text = Encoding.UTF8.GetString(buffer, 0, count);
Console.WriteLine(text);
exitEvent.Set();
}
}
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
exitEvent = new ManualResetEvent(false);
var webSocket = new ClientWebSocket();
string uri = "wss://localhost:8333/api/ws";
Console.WriteLine("Connecting to {0}", uri);
try
{
webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).GetAwaiter().GetResult();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
Console.WriteLine("Connected");
Action receive = null;
receive = delegate
{
byte[] buffer = new byte[32768];
webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).ContinueWith(t =>
{
if (t.IsFaulted)
{
Console.WriteLine("Receive fault.");
return;
}
if (t.IsCanceled)
{
Console.WriteLine("Cancel fault.");
return;
}
HandleMessage(t.Result.MessageType, buffer, t.Result.Count);
receive();
});
};
receive();
exitEvent.WaitOne();
}
}
}
我通过运行 xbuild 构建了这个程序。
杰特森纳米;Linux 4.9.140-tegra aarch64;单声道 4.6.2;