Trying to use .net core server as a WebSocket client to open multiple connections to a rocket.chat server, I'm opening a new thread per connection since the socket server requires an answer to a ping request every couple of seconds. The problem here is after calling the start method for the child thread the rest of the parent thread's code is not being executed and I could find neither the reason nor the solution.
Here's the Websocket class
public class WebSocket
{
private Guid Id;
private ClientWebSocket Client;
private CancellationToken Token;
private readonly ILogger<WebSocket> Logger;
public WebSocket(Guid id, ILogger<WebSocket> logger)
{
Id = id;
Logger = logger;
Client = new ClientWebSocket();
Token = new CancellationToken();
}
public Guid GetId()
{
return Id;
}
public async void Init()
{
await Connect();
await Pong();
return;
}
public async Task Connect()
{
var uri = new Uri("wss://<DNS>/websocket");
await Client.ConnectAsync(uri, Token);
while (true)
{
Console.WriteLine(Client.State);
if (Client.State == WebSocketState.Open)
{
Send("{\"msg\":\"connect\",\"version\":\"1\",\"support\":[\"1\"]}");
break;
}
}
while (true)
{
var res = await Recieve();
if (res.Contains("connected"))
{
Logger.LogInformation("Web socket successfully connected for user {User.Guid}", Id);
return;
}
}
}
public async Task<bool> Close()
{
await Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", Token);
if (Client.State == WebSocketState.Closed)
{
return true;
}
else
{
return false;
}
}
public async void Send(string data)
{
while (true) if (Client.State == WebSocketState.Open) break;
var encoded = Encoding.UTF8.GetBytes(data);
var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);
await Client.SendAsync(buffer, WebSocketMessageType.Text, true, Token);
Console.WriteLine("Sent: " + data);
}
public async Task<string> Recieve()
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
var res = await Client.ReceiveAsync(buffer, Token);
return Encoding.UTF8.GetString(buffer.Array, 0, res.Count);
}
public async Task Pong()
{
while (Client.State == WebSocketState.Open)
{
var res = await Recieve();
if (res.Contains("ping"))
{
Send("{\"msg\": \"pong\"}");
Console.WriteLine(res);
}
Thread.Sleep(10000);
}
}
}
Here's the object creation and starting it on a new thread
var socket = new WebSocket(guid, _socketLogger);
Thread thread = new Thread(new ThreadStart(socket.Init));
Sockets.webSockets.Add(socket, thread);
thread.IsBackground = true;
thread.Start();
// what ever is here is not being executed
UPDATE
So I removed the thread usage and avoided the unawaitable asyncs, also removed the first while loop in connect cause it was pointed out to be useless.
The calling now starts with await socket.Init() but still I'm facing the same issue...
Output (after 30s)
Open
Web socket successfully connected for user <user guid>
{"msg": "ping"}"
Sent: {"msg": "pong"}
{"msg": "ping"}
Sent: {"msg": "pong"}
{"msg": "ping"}
Sent: {"msg": "pong"}
and this continues on while there's other stuff to write on the console after init()