0

I'm trying to implement Websockets in c# and i tried many ways but nothing works fine.

i) working fine with ClientwebSocket class but this class don't have events(i need events)

ii) tried with WebSocketSharp.WebSocket class but closing immediately after opening connection

iii) WebSocket4Net.WebSocket same problem closing connection immediately

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

1 Answer 1

4

I hope that your issue is with the using in the code. 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).

That means after executing the 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:

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

Don't forget to dispose the object after use.

Sign up to request clarification or add additional context in comments.

4 Comments

And most likely make the variable into a class field so it stays alive and can be disposed at later time.
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(); even this didnt worked,facing same issue
@SaigeethaReddyMahakala: enclose them inside a try..catch and get the exception details
@sujith karivelil: i tried it but its not throwing any exception directly jumping to onClose() but i captured the eventArgs in Onclose() its saying that "An exception occured while connnecting"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.