ClientWebSocket - SocketException: No connection could be made

0

I am trying to connect to WebSocket server (demo or localhost) using ClientWebSocket. I get an exception:

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

I also have JavaScript websocket client which connected succefully. Why I can't connect using 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...");
                                                         
            }

        }
    }
}
c#
.net
asp.net-core
websocket
asked on Stack Overflow Jul 22, 2020 by miuosh • edited Jul 23, 2020 by miuosh

1 Answer

1

UPDATE 24/07

I write simple WebSocket server in nodejs to test connection on localhost. My websocket web client connected successfully but console app failed to connect every time.

If so, it doesn't make sense. It works on me.

enter image description here

There are codes of ws client in .net console application.

    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);
    }

There are ws codes of my node.js server with 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 can not directly connect to socket.io in Python.

Here is a solution from @Jim Stott. There is a project on CodePlex ( NuGet as well ) that is a C# client for socket.io.

Example client style:

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

And also there are many ways to meet your needs from the question below.
Communicating with a socket.io server via c#

Here is the article about WebSocket vs Socket.io

answered on Stack Overflow Jul 23, 2020 by Michael Wang • edited Jul 24, 2020 by Michael Wang

User contributions licensed under CC BY-SA 3.0