我在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构建了该程序。
Jetson Nano; Linux 4.9.140-tegra aarch64;单声道4.6.2;