Search code examples
c#.netwebsocketclientwebsocket

Calling ConnectAsync to a ClientWebSocket exits the method with no exception


I can't get this websocket to connect. I ran this in debug mode. Once I let the socket.ConnectAsync() call run, the program thinks for a second and exits the method call without throwing an exception. Anyone know what is going on/how to help me? I know the uri is valid because it reaches the same string that works in my javascript implementation

    // class WebSocketClient
    public static async Task<SpeakItClient> Connect(AuthCredentials credentials) {
        var client = new SpeakItClient(credentials);
        await client.ConnectAsync();
        return client;
    }
    
    public async Task<bool> ConnectAsync() {
        if (socket?.State is WebSocketState.Connecting or WebSocketState.Open)
            return false;
        
        var uri = "...";

        socket?.Dispose();
        socket = new ClientWebSocket();

        Console.WriteLine("Narrowing down #1");
        await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
        Console.WriteLine("Narrowing down #2");

        ...
        return true;
    }

Here is the code I'm using to test it:

    public static void Main(string[] args) {
        Console.WriteLine("Starting");
        try {
            var client = WebSocketClient.Connect(new AuthCredentials {
                id = "collidacube",
                password = "amazinggrace"
            });
        }
        catch (Exception e) {
            Console.WriteLine(e.Message);
        }

        Console.WriteLine("Exiting");
    }

The output I get is:

Starting
Narrowing down #1
Exiting

Solution

  • After a hassle with ChatGPT, I realized that I forgot to add the async modifier to the Main method and await the response from WebSocketClient.Connect().