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