【问题标题】:ClientWebSocket - SocketException: No connection could be madeClientWebSocket - SocketException:无法建立连接
【发布时间】: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


【解决方案1】:

24/07 更新

我在 nodejs 中编写简单的 WebSocket 服务器来测试连接 本地主机。我的 websocket 网络客户端连接成功,但控制台 应用每次都连接失败。

如果是这样,那就没有意义了。它对我有用。

.netconsole application中有ws客户端的代码。

    static async Task Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        
        try
        {
            Console.WriteLine("Press Ctrl+C to end.");
            await ConnectAsync("ws://localhost:8080");
            //await ConnectAsync("ws://demos.kaazing.com/echo");

            Console.ReadLine();
        }
        catch (OperationCanceledException)
        {
            // This is the normal way we close.
        }

    }

    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...");


            await Send(socket, "Hello from client.");
            await Receive(socket);

            await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "close", CancellationToken.None);

        }

    }

    static async Task Send(ClientWebSocket socket, string data) =>
await socket.SendAsync(Encoding.UTF8.GetBytes(data), WebSocketMessageType.Text, true, CancellationToken.None);


    static async Task Receive(ClientWebSocket socket)
    {
        var buffer = new ArraySegment<byte>(new byte[2048]);
        do
        {
            WebSocketReceiveResult result;
            using (var ms = new MemoryStream())
            {
                do
                {
                    result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                    ms.Write(buffer.Array, buffer.Offset, result.Count);
                } while (!result.EndOfMessage);

                if (result.MessageType == WebSocketMessageType.Close)
                    break;

                ms.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(ms, Encoding.UTF8))
                    Console.WriteLine(await reader.ReadToEndAsync());
            }
        } while (true);
    }

我的node.js服务器有ws代码和websocket。

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received message => ${message}`)
  })
  ws.send('Hello from server!')
})

console.log('Server running at ws://127.0.0.1:8080');


_________________________________________________________

ClientWebSocket 无法在 Python 中直接连接到 socket.io。

这是来自 @Jim Stott 的解决方案。 CodePlex(也有 NuGet)上有一个项目,它是 socket.io 的 C# 客户端。

示例客户端样式:

socket.On("news", (data) =>    {
Console.WriteLine(data);
});

还有很多方法可以满足您的需求。
Communicating with a socket.io server via c#

这是关于WebSocket vs Socket.io

的文章

【讨论】:

  • 但是我不想安装socket.io。我想使用 System.Net.WebSockets 连接到 websocket 服务器。
  • 对不起,我以为你之前使用 socket.io 构建 ws 服务器。
  • 好的。我认为这样代码应该可以工作。谢谢你的努力。我会继续寻找解决方案。
  • 如果没有关联代码,可以检查防火墙或操作系统版本(Win 8 later)。希望你得到正确的答案。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
相关资源
最近更新 更多