【发布时间】:2020-07-22 13:41:24
【问题描述】:
我正在尝试使用 ClientWebSocket 连接到 WebSocket 服务器(演示或本地主机)。 我得到一个例外:
System.Net.WebSockets.WebSocketException
HResult=0x80004005
Message=Unable to connect to the remote server
Source=System.Net.WebSockets.Client
StackTrace:
Inner Exception 1:
HttpRequestException: No connection could be made because the target machine actively refused it
Inner Exception 2:
SocketException: No connection could be made because the target machine actively refused it
我也有成功连接的 JavaScript websocket 客户端。为什么我无法使用 ClientWebSocket 连接?
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using StreamJsonRpc;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
try
{
Console.WriteLine("Press Ctrl+C to end.");
//await ConnectAsync("ws://localhost:63762/ws");
await ConnectAsync("ws://demos.kaazing.com/echo");
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
}
static async Task ConnectAsync(string url)
{
using (var socket = new ClientWebSocket())
{
Console.WriteLine("---> JSON-RPC Client connecting to " + url);
await socket.ConnectAsync(new Uri(url), CancellationToken.None);
Console.WriteLine("-> Connected to web socket. Establishing JSON-RPC protocol...");
}
}
}
}
【问题讨论】:
-
等待 ConnectAsync("ws://demos.kaazing.com/echo"); url是连接失败的主要原因。更改其他 ws 服务器进行测试。 websocket.org/echo.html
-
当我用其他 ws 服务器测试你的代码时它可以工作。
-
我在 nodejs 中编写了简单的 WebSocket 服务器来测试本地主机上的连接。我的 websocket 网络客户端连接成功,但控制台应用每次都连接失败。
-
我已经更新了我的代码,它对我有效,你能检查一下区别吗?
-
更新到 .Net Core 3.1 解决了我的问题。
标签: c# .net asp.net-core websocket