I created a console dot net core project and it listens to a websocket server and it displays information received.
var url = $"wss://serverurl";
var ws = new WebSocket(url);
ws.OnOpen += (s, ev) =>
{
Console.WriteLine("web socket opened");
};
ws.OnMessage += (s, ev) =>
{
Console.WriteLine(s.Data);
};
ws.OnClose += (s, ev) =>
{
Console.WriteLine("web socket will be closed");
};
ws.OnError += (s, ev) =>
{
ws.Close();
};
ws.Connect();
But the console will close immediately after ws.Connect()
is executed.
Or if I put Console.Read()
then console will wait for input key and won't display info here anymore.
How to proceed here ?
I created console app to be executed on Windows or even Linux environment.
Try
while(true)
Thread.Sleep(1000);
to sleep indefinitely in mail thread.
This project is a good demo for C# to always listen for a request on a port.
The code is here: https://github.com/Anduin2017/Genji/blob/master/Genji/Models/GenjiServer.cs#L64
private async Task Listening()
{
while (true)
{
var listener = new TcpListener(IPAddress.Any, Port);
try
{
listener.Start();
Console.ResetColor();
Console.WriteLine($"Genji server started at http://localhost:{Port}/");
while (true)
{
var tcp = await listener.AcceptTcpClientAsync();
var stream = tcp.GetStream();
Excute(stream).GetAwaiter();
}
}
catch (Exception e)
{
Recorder.RecordException(e);
listener.Stop();
await Task.Delay(5000);
}
}
}
private async Task Excute(NetworkStream stream)
{
Recorder.RecordIncoming();
try
{
await Calculate(stream);
}
catch (RequestTerminatedException)
{
Recorder.Print("A request was terminated!");
}
catch (Exception e)
{
stream.Dispose();
Recorder.RecordException(e);
}
}
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.