简体   繁体   English

Websocket连接在C#中连接后立即关闭

[英]Websocket connection closing immediately after connection in c#

I'm trying to implement Websockets in c# and i tried many ways but nothing works fine. 我正在尝试在C#中实现Websockets ,我尝试了许多方法,但没有任何效果。

i) working fine with ClientwebSocket class but this class don't have events(i need events) 我)与ClientwebSocket类一起正常工作,但此类没有事件(我需要事件)

ii) tried with WebSocketSharp.WebSocket class but closing immediately after opening connection ii)尝试使用WebSocketSharp.WebSocket类,但在打开连接后立即关闭

iii) WebSocket4Net.WebSocket same problem closing connection immediately iii)WebSocket4Net.WebSocket同样的问题,立即关闭连接

can anyone please help me in solving this issue.A big thanks in advance. 谁能帮助我解决这个问题。在此先多谢。

class SocketConnection
{
    public static WebSocketSharp.WebSocket client;

    public void connectionEstablish()
    {
        //---------------------------WebSocketSharp ----------------------------

        using (client = new WebSocketSharp.WebSocket("ws://localhost:8182"))
        {
            client.OnClose += new EventHandler<CloseEventArgs>(onClosed);
            client.OnMessage += new EventHandler<MessageEventArgs>(onReceived);
            client.OnOpen += new EventHandler(OnConnectionOpen);

            client.Connect();

        }
      }
    public static void onClosed(object sender, EventArgs e)
    {
      Console.WriteLine("Inclose");
    }
    public static void onReceived(object sender, MessageEventArgs e)
    {
      Console.WriteLine("received");
    }
    public void OnConnectionOpen(object sender, EventArgs e)
    {
      Console.WriteLine("opened connection");
    }
}

I hope that your issue is with the using in the code. 我希望您的问题与代码中的using有关。 The variable client is an using variable so It will get disposed when using block ends(That is what the purpose of using, calling dispose automatically). 变量client是一个using变量,因此在使用代码块结尾时将被处置(这是使用目的,自动调用dispose)。

That means after executing the client.Connect(); 这意味着在执行client.Connect();之后client.Connect(); using block ends and hence the object get disposed. 使用块末端,因此将对象丢弃。 To verify this, try remove the using block and change the code like the following: 要验证这一点,请尝试删除using块并更改代码,如下所示:

var client = new WebSocketSharp.WebSocket("ws://localhost:8182");

Don't forget to dispose the object after use. 使用后不要忘记处理该物体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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