简体   繁体   中英

C# .net WebSocket client never disconnects

Been using C# Websocket client in my app using System.Net.WebSockets. All my code to send and receive is working well, however I can not for the life of me successfully disconnect (Which i need to do so i can then use the client again w/ different hostname). I have created a quick demo to show my problem.

This is my Program code:

class Program
{
    static void Main(string[] args)
    {
        GetDocList();

        Console.ReadLine();
    }
    static async Task<string> GetDocList()
    {
        var client = new myWSClient(new Uri("ws://localhost:9999/qlcplusWS"));
        var docs = await client.ConnectAndDisconnect();
        return docs;
    }

}

This is my Class that I am using

public class myWSClient
{

    private ClientWebSocket _client;
    public Uri _myURI;
    public myWSClient(Uri MyURI)
    {
        _client = new ClientWebSocket();
        _myURI = MyURI;
    }

    public async Task<string> ConnectAndDisconnect()
    {
        string dummyreturn = "";
        await _client.ConnectAsync(_myURI, CancellationToken.None);
        Console.WriteLine("Connected");
        string status = "";
        Console.WriteLine("Waiting to Disconnect, but it will never happen :(");
        await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, status, CancellationToken.None);
        Console.WriteLine("Disconnected mate");
        return dummyreturn;
    }

}

Am I using the wrong method or is my code just syntactically wrong?

您必须等待方法返回,因为这些方法是异步的,并且在启动GetDocList()方法的任务后,主函数将继续执行。

GetDocList().Wait();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM