Listener in a task works only one time Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Calculate relative time in C#How do I make a textbox that only accepts numbers?Random number generator only generating one random numberHow to check internet access on Android? InetAddress never times outHow would I run an async Task<T> method synchronously?How to remove time portion of date in C# in DateTime object only?async/await - when to return a Task vs void?What C# AES encryption options to use so result can be decrypted on a public web site?Linkedin api post not work?Socket.io authenticating as a client

Second order approximation of the loss function (Deep learning book, 7.33)

Are all CP/M-80 implementations binary compatible?

Would reducing the reference voltage of an ADC have any effect on accuracy?

What is it called when you ride around on your front wheel?

Do I need to protect SFP ports and optics from dust/contaminants? If so, how?

How to keep bees out of canned beverages?

Where did Arya get these scars?

Does Mathematica have an implementation of the Poisson Binomial Distribution?

What is the best way to deal with NPC-NPC combat?

What to do with someone that cheated their way through university and a PhD program?

How to open locks without disable device?

Mistake in years of experience in resume?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Justification for leaving new position after a short time

What ability score does a Hexblade's Pact Weapon use for attack and damage when wielded by another character?

Is it OK if I do not take the receipt in Germany?

How to get even lighting when using flash for group photos near wall?

finding a tangent line to a parabola

Protagonist's race is hidden - should I reveal it?

Is Electric Central Heating worth it if using Solar Panels?

My admission is revoked after accepting the admission offer

Why did Israel vote against lifting the American embargo on Cuba?

Raising a bilingual kid. When should we introduce the majority language?

What is the term for a person whose job is to place products on shelves in stores?



Listener in a task works only one time



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Calculate relative time in C#How do I make a textbox that only accepts numbers?Random number generator only generating one random numberHow to check internet access on Android? InetAddress never times outHow would I run an async Task<T> method synchronously?How to remove time portion of date in C# in DateTime object only?async/await - when to return a Task vs void?What C# AES encryption options to use so result can be decrypted on a public web site?Linkedin api post not work?Socket.io authenticating as a client



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have written a complex class called DonationListener. This class has a property named onDonation that takes a function that will be called when a donation happens. In a simple console program it works fine, but in the more complex WinForms application - not. I am pretty sure that there is no mistake in the class. So I think the problem is in the usage of it. My class works with WebSockets, so I decided to check with the fiddler if the connection lost after the first donation event, and the answer is no, the connection is fine and sending packages that should invoke onDonation. Here's the code



public string donation_password;
DonationListener dl;

public System.Windows.Forms.PictureBox[,] eliteCards;
public mainForm()

InitializeComponent();
initializeDonation();


public void initializeDonation()

donation_password = db.getPassword();
dl = new DonationListener(donation_password);
dl.OnDonation = donation =>

overlay ol = new overlay();
string username = donation["username"].ToString();
User toRide = db.getUserByField(username);
ol.Show();
ol.ride(toRide);
;

Task t = new Task(() =>
dl.DoListen();
);
t.Start();



Full class DonationListener(if u need sth from it)



using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RacheM

public class DonationListener

private string addUserTemplate = "69:42["add-user","token":"0","type":"alert_widget"]";


public Action<JObject> OnDonation = null;
private readonly string _token;

public DonationListener(string token)

_token = token;


public void DoListen()

var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();



private static string ExtractToken(string strWidthToken)

var m = Regex.Match(strWidthToken, ""sid":"(?<token>[^"]+)"");
return m.Groups["token"].Value;


private static string DoRequest(string method, string url, string data = "", Cookie cookie = null)

var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

httpWebRequest.Method = method;
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add("Origin", "https://www.donationalerts.com");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";

httpWebRequest.Referer = "https://www.donationalerts.com/widget/alerts?group_id=1&token=mcq71m8KVIsojvo5ukFZ";
if (method == "GET")

//httpWebRequest.Headers.Remove("Content-Length");
httpWebRequest.ContentLength = 0;

else

httpWebRequest.ContentType = "text/plain;charset=UTF-8";


if (cookie != null)

if (httpWebRequest.CookieContainer == null)

httpWebRequest.CookieContainer = new CookieContainer();


httpWebRequest.CookieContainer.Add(cookie);


if (method == "POST" && !string.IsNullOrEmpty(data))

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();



var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

var streamReader = new StreamReader(httpResponse.GetResponseStream());

if(streamReader == null)

throw new Exception("Connection error");


using (streamReader)

return streamReader.ReadToEnd();



private async Task DoWebSocket(string url, Cookie cookie)

using (var ws = new ClientWebSocket())

var serverUri = new Uri(url);
ws.Options.Cookies = new CookieContainer();
ws.Options.Cookies.Add(cookie);
await ws.ConnectAsync(serverUri, CancellationToken.None);
var cts = new CancellationTokenSource();

Task.Factory.StartNew(
async () =>

while (true)

try

string srcMessage = string.Empty;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

using (var ms = new MemoryStream())

WebSocketReceiveResult result= null;
do

result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)

using (var reader = new StreamReader(ms, Encoding.UTF8))

srcMessage = reader.ReadToEnd();




if (string.IsNullOrEmpty(srcMessage)) continue;


if (srcMessage.IndexOf("42["donation", StringComparison.Ordinal) == 0)

OnDonation?.Invoke(ParseDonateMessage(srcMessage));

else

Console.WriteLine("no donate msg: " + srcMessage);


catch (Exception ex)

Console.WriteLine("Error: " + ex.Message);


, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

await SendWsMessage(ws, "2probe");
await SendWsMessage(ws, "5");
while (ws.State == WebSocketState.Open)

await SendWsMessage(ws, "2");
Thread.Sleep(25000);




private static async Task SendWsMessage(WebSocket ws, string message)

var sendBytes = Encoding.UTF8.GetBytes(message);
var cts = new CancellationTokenSource();
var sendBuffer = new ArraySegment<byte>(sendBytes);
await
ws.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage: true,
cancellationToken: cts.Token);


private static JObject ParseDonateMessage(string rcvMsg)

rcvMsg = rcvMsg.Replace("42["donation","", "");
rcvMsg = rcvMsg.Substring(0, rcvMsg.Length - 2);
return (JObject)JsonConvert.DeserializeObject(Regex.Unescape(rcvMsg));












share|improve this question
























  • Can you show use the code of DoListen? Because, why do you think it should 'loop'?

    – J. van Langen
    Mar 22 at 15:37












  • I've added the full class.

    – MrLalatg
    Mar 22 at 15:40







  • 2





    Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

    – Panagiotis Kanavos
    Mar 22 at 15:51











  • The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

    – J. van Langen
    Mar 22 at 15:53







  • 1





    The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

    – Panagiotis Kanavos
    Mar 22 at 15:54


















0















I have written a complex class called DonationListener. This class has a property named onDonation that takes a function that will be called when a donation happens. In a simple console program it works fine, but in the more complex WinForms application - not. I am pretty sure that there is no mistake in the class. So I think the problem is in the usage of it. My class works with WebSockets, so I decided to check with the fiddler if the connection lost after the first donation event, and the answer is no, the connection is fine and sending packages that should invoke onDonation. Here's the code



public string donation_password;
DonationListener dl;

public System.Windows.Forms.PictureBox[,] eliteCards;
public mainForm()

InitializeComponent();
initializeDonation();


public void initializeDonation()

donation_password = db.getPassword();
dl = new DonationListener(donation_password);
dl.OnDonation = donation =>

overlay ol = new overlay();
string username = donation["username"].ToString();
User toRide = db.getUserByField(username);
ol.Show();
ol.ride(toRide);
;

Task t = new Task(() =>
dl.DoListen();
);
t.Start();



Full class DonationListener(if u need sth from it)



using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RacheM

public class DonationListener

private string addUserTemplate = "69:42["add-user","token":"0","type":"alert_widget"]";


public Action<JObject> OnDonation = null;
private readonly string _token;

public DonationListener(string token)

_token = token;


public void DoListen()

var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();



private static string ExtractToken(string strWidthToken)

var m = Regex.Match(strWidthToken, ""sid":"(?<token>[^"]+)"");
return m.Groups["token"].Value;


private static string DoRequest(string method, string url, string data = "", Cookie cookie = null)

var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

httpWebRequest.Method = method;
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add("Origin", "https://www.donationalerts.com");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";

httpWebRequest.Referer = "https://www.donationalerts.com/widget/alerts?group_id=1&token=mcq71m8KVIsojvo5ukFZ";
if (method == "GET")

//httpWebRequest.Headers.Remove("Content-Length");
httpWebRequest.ContentLength = 0;

else

httpWebRequest.ContentType = "text/plain;charset=UTF-8";


if (cookie != null)

if (httpWebRequest.CookieContainer == null)

httpWebRequest.CookieContainer = new CookieContainer();


httpWebRequest.CookieContainer.Add(cookie);


if (method == "POST" && !string.IsNullOrEmpty(data))

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();



var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

var streamReader = new StreamReader(httpResponse.GetResponseStream());

if(streamReader == null)

throw new Exception("Connection error");


using (streamReader)

return streamReader.ReadToEnd();



private async Task DoWebSocket(string url, Cookie cookie)

using (var ws = new ClientWebSocket())

var serverUri = new Uri(url);
ws.Options.Cookies = new CookieContainer();
ws.Options.Cookies.Add(cookie);
await ws.ConnectAsync(serverUri, CancellationToken.None);
var cts = new CancellationTokenSource();

Task.Factory.StartNew(
async () =>

while (true)

try

string srcMessage = string.Empty;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

using (var ms = new MemoryStream())

WebSocketReceiveResult result= null;
do

result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)

using (var reader = new StreamReader(ms, Encoding.UTF8))

srcMessage = reader.ReadToEnd();




if (string.IsNullOrEmpty(srcMessage)) continue;


if (srcMessage.IndexOf("42["donation", StringComparison.Ordinal) == 0)

OnDonation?.Invoke(ParseDonateMessage(srcMessage));

else

Console.WriteLine("no donate msg: " + srcMessage);


catch (Exception ex)

Console.WriteLine("Error: " + ex.Message);


, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

await SendWsMessage(ws, "2probe");
await SendWsMessage(ws, "5");
while (ws.State == WebSocketState.Open)

await SendWsMessage(ws, "2");
Thread.Sleep(25000);




private static async Task SendWsMessage(WebSocket ws, string message)

var sendBytes = Encoding.UTF8.GetBytes(message);
var cts = new CancellationTokenSource();
var sendBuffer = new ArraySegment<byte>(sendBytes);
await
ws.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage: true,
cancellationToken: cts.Token);


private static JObject ParseDonateMessage(string rcvMsg)

rcvMsg = rcvMsg.Replace("42["donation","", "");
rcvMsg = rcvMsg.Substring(0, rcvMsg.Length - 2);
return (JObject)JsonConvert.DeserializeObject(Regex.Unescape(rcvMsg));












share|improve this question
























  • Can you show use the code of DoListen? Because, why do you think it should 'loop'?

    – J. van Langen
    Mar 22 at 15:37












  • I've added the full class.

    – MrLalatg
    Mar 22 at 15:40







  • 2





    Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

    – Panagiotis Kanavos
    Mar 22 at 15:51











  • The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

    – J. van Langen
    Mar 22 at 15:53







  • 1





    The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

    – Panagiotis Kanavos
    Mar 22 at 15:54














0












0








0








I have written a complex class called DonationListener. This class has a property named onDonation that takes a function that will be called when a donation happens. In a simple console program it works fine, but in the more complex WinForms application - not. I am pretty sure that there is no mistake in the class. So I think the problem is in the usage of it. My class works with WebSockets, so I decided to check with the fiddler if the connection lost after the first donation event, and the answer is no, the connection is fine and sending packages that should invoke onDonation. Here's the code



public string donation_password;
DonationListener dl;

public System.Windows.Forms.PictureBox[,] eliteCards;
public mainForm()

InitializeComponent();
initializeDonation();


public void initializeDonation()

donation_password = db.getPassword();
dl = new DonationListener(donation_password);
dl.OnDonation = donation =>

overlay ol = new overlay();
string username = donation["username"].ToString();
User toRide = db.getUserByField(username);
ol.Show();
ol.ride(toRide);
;

Task t = new Task(() =>
dl.DoListen();
);
t.Start();



Full class DonationListener(if u need sth from it)



using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RacheM

public class DonationListener

private string addUserTemplate = "69:42["add-user","token":"0","type":"alert_widget"]";


public Action<JObject> OnDonation = null;
private readonly string _token;

public DonationListener(string token)

_token = token;


public void DoListen()

var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();



private static string ExtractToken(string strWidthToken)

var m = Regex.Match(strWidthToken, ""sid":"(?<token>[^"]+)"");
return m.Groups["token"].Value;


private static string DoRequest(string method, string url, string data = "", Cookie cookie = null)

var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

httpWebRequest.Method = method;
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add("Origin", "https://www.donationalerts.com");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";

httpWebRequest.Referer = "https://www.donationalerts.com/widget/alerts?group_id=1&token=mcq71m8KVIsojvo5ukFZ";
if (method == "GET")

//httpWebRequest.Headers.Remove("Content-Length");
httpWebRequest.ContentLength = 0;

else

httpWebRequest.ContentType = "text/plain;charset=UTF-8";


if (cookie != null)

if (httpWebRequest.CookieContainer == null)

httpWebRequest.CookieContainer = new CookieContainer();


httpWebRequest.CookieContainer.Add(cookie);


if (method == "POST" && !string.IsNullOrEmpty(data))

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();



var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

var streamReader = new StreamReader(httpResponse.GetResponseStream());

if(streamReader == null)

throw new Exception("Connection error");


using (streamReader)

return streamReader.ReadToEnd();



private async Task DoWebSocket(string url, Cookie cookie)

using (var ws = new ClientWebSocket())

var serverUri = new Uri(url);
ws.Options.Cookies = new CookieContainer();
ws.Options.Cookies.Add(cookie);
await ws.ConnectAsync(serverUri, CancellationToken.None);
var cts = new CancellationTokenSource();

Task.Factory.StartNew(
async () =>

while (true)

try

string srcMessage = string.Empty;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

using (var ms = new MemoryStream())

WebSocketReceiveResult result= null;
do

result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)

using (var reader = new StreamReader(ms, Encoding.UTF8))

srcMessage = reader.ReadToEnd();




if (string.IsNullOrEmpty(srcMessage)) continue;


if (srcMessage.IndexOf("42["donation", StringComparison.Ordinal) == 0)

OnDonation?.Invoke(ParseDonateMessage(srcMessage));

else

Console.WriteLine("no donate msg: " + srcMessage);


catch (Exception ex)

Console.WriteLine("Error: " + ex.Message);


, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

await SendWsMessage(ws, "2probe");
await SendWsMessage(ws, "5");
while (ws.State == WebSocketState.Open)

await SendWsMessage(ws, "2");
Thread.Sleep(25000);




private static async Task SendWsMessage(WebSocket ws, string message)

var sendBytes = Encoding.UTF8.GetBytes(message);
var cts = new CancellationTokenSource();
var sendBuffer = new ArraySegment<byte>(sendBytes);
await
ws.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage: true,
cancellationToken: cts.Token);


private static JObject ParseDonateMessage(string rcvMsg)

rcvMsg = rcvMsg.Replace("42["donation","", "");
rcvMsg = rcvMsg.Substring(0, rcvMsg.Length - 2);
return (JObject)JsonConvert.DeserializeObject(Regex.Unescape(rcvMsg));












share|improve this question
















I have written a complex class called DonationListener. This class has a property named onDonation that takes a function that will be called when a donation happens. In a simple console program it works fine, but in the more complex WinForms application - not. I am pretty sure that there is no mistake in the class. So I think the problem is in the usage of it. My class works with WebSockets, so I decided to check with the fiddler if the connection lost after the first donation event, and the answer is no, the connection is fine and sending packages that should invoke onDonation. Here's the code



public string donation_password;
DonationListener dl;

public System.Windows.Forms.PictureBox[,] eliteCards;
public mainForm()

InitializeComponent();
initializeDonation();


public void initializeDonation()

donation_password = db.getPassword();
dl = new DonationListener(donation_password);
dl.OnDonation = donation =>

overlay ol = new overlay();
string username = donation["username"].ToString();
User toRide = db.getUserByField(username);
ol.Show();
ol.ride(toRide);
;

Task t = new Task(() =>
dl.DoListen();
);
t.Start();



Full class DonationListener(if u need sth from it)



using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RacheM

public class DonationListener

private string addUserTemplate = "69:42["add-user","token":"0","type":"alert_widget"]";


public Action<JObject> OnDonation = null;
private readonly string _token;

public DonationListener(string token)

_token = token;


public void DoListen()

var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();



private static string ExtractToken(string strWidthToken)

var m = Regex.Match(strWidthToken, ""sid":"(?<token>[^"]+)"");
return m.Groups["token"].Value;


private static string DoRequest(string method, string url, string data = "", Cookie cookie = null)

var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

httpWebRequest.Method = method;
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add("Origin", "https://www.donationalerts.com");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";

httpWebRequest.Referer = "https://www.donationalerts.com/widget/alerts?group_id=1&token=mcq71m8KVIsojvo5ukFZ";
if (method == "GET")

//httpWebRequest.Headers.Remove("Content-Length");
httpWebRequest.ContentLength = 0;

else

httpWebRequest.ContentType = "text/plain;charset=UTF-8";


if (cookie != null)

if (httpWebRequest.CookieContainer == null)

httpWebRequest.CookieContainer = new CookieContainer();


httpWebRequest.CookieContainer.Add(cookie);


if (method == "POST" && !string.IsNullOrEmpty(data))

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();



var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

var streamReader = new StreamReader(httpResponse.GetResponseStream());

if(streamReader == null)

throw new Exception("Connection error");


using (streamReader)

return streamReader.ReadToEnd();



private async Task DoWebSocket(string url, Cookie cookie)

using (var ws = new ClientWebSocket())

var serverUri = new Uri(url);
ws.Options.Cookies = new CookieContainer();
ws.Options.Cookies.Add(cookie);
await ws.ConnectAsync(serverUri, CancellationToken.None);
var cts = new CancellationTokenSource();

Task.Factory.StartNew(
async () =>

while (true)

try

string srcMessage = string.Empty;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

using (var ms = new MemoryStream())

WebSocketReceiveResult result= null;
do

result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)

using (var reader = new StreamReader(ms, Encoding.UTF8))

srcMessage = reader.ReadToEnd();




if (string.IsNullOrEmpty(srcMessage)) continue;


if (srcMessage.IndexOf("42["donation", StringComparison.Ordinal) == 0)

OnDonation?.Invoke(ParseDonateMessage(srcMessage));

else

Console.WriteLine("no donate msg: " + srcMessage);


catch (Exception ex)

Console.WriteLine("Error: " + ex.Message);


, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

await SendWsMessage(ws, "2probe");
await SendWsMessage(ws, "5");
while (ws.State == WebSocketState.Open)

await SendWsMessage(ws, "2");
Thread.Sleep(25000);




private static async Task SendWsMessage(WebSocket ws, string message)

var sendBytes = Encoding.UTF8.GetBytes(message);
var cts = new CancellationTokenSource();
var sendBuffer = new ArraySegment<byte>(sendBytes);
await
ws.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage: true,
cancellationToken: cts.Token);


private static JObject ParseDonateMessage(string rcvMsg)

rcvMsg = rcvMsg.Replace("42["donation","", "");
rcvMsg = rcvMsg.Substring(0, rcvMsg.Length - 2);
return (JObject)JsonConvert.DeserializeObject(Regex.Unescape(rcvMsg));









c# winforms asynchronous websocket






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 15:49









demo

2,46144084




2,46144084










asked Mar 22 at 15:34









MrLalatgMrLalatg

627




627












  • Can you show use the code of DoListen? Because, why do you think it should 'loop'?

    – J. van Langen
    Mar 22 at 15:37












  • I've added the full class.

    – MrLalatg
    Mar 22 at 15:40







  • 2





    Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

    – Panagiotis Kanavos
    Mar 22 at 15:51











  • The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

    – J. van Langen
    Mar 22 at 15:53







  • 1





    The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

    – Panagiotis Kanavos
    Mar 22 at 15:54


















  • Can you show use the code of DoListen? Because, why do you think it should 'loop'?

    – J. van Langen
    Mar 22 at 15:37












  • I've added the full class.

    – MrLalatg
    Mar 22 at 15:40







  • 2





    Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

    – Panagiotis Kanavos
    Mar 22 at 15:51











  • The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

    – J. van Langen
    Mar 22 at 15:53







  • 1





    The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

    – Panagiotis Kanavos
    Mar 22 at 15:54

















Can you show use the code of DoListen? Because, why do you think it should 'loop'?

– J. van Langen
Mar 22 at 15:37






Can you show use the code of DoListen? Because, why do you think it should 'loop'?

– J. van Langen
Mar 22 at 15:37














I've added the full class.

– MrLalatg
Mar 22 at 15:40






I've added the full class.

– MrLalatg
Mar 22 at 15:40





2




2





Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

– Panagiotis Kanavos
Mar 22 at 15:51





Tasks aren't threads. There's no need to create a cold task and "start" it with Task.Start. They are promises that something will produce a value in the future. Your code starts multiple tasks though without awaiting them, blocks them, starts more tasks inside other tasks.

– Panagiotis Kanavos
Mar 22 at 15:51













The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

– J. van Langen
Mar 22 at 15:53






The while (ws.State == WebSocketState.Open) blocks the current thread. which is probably the gui thread in a winform application.

– J. van Langen
Mar 22 at 15:53





1




1





The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

– Panagiotis Kanavos
Mar 22 at 15:54






The initializeDonation method fires off a task just once and never awaits it. This means that anything in that method will be garbage collected when the method ends. This won't work any differently in the console application.

– Panagiotis Kanavos
Mar 22 at 15:54













1 Answer
1






active

oldest

votes


















0














Maybe you should try to make this function repeat itself by:



bool RunFlag = true // can be set to false somewhere else
public void DoListen()

while(RunFlag)
var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();







share|improve this answer























  • The problem is not in the class. Cuz' in the simple console application it works fine

    – MrLalatg
    Mar 22 at 18:27











  • At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

    – ElDuderino
    Mar 22 at 18:45











  • Cuz' if what he says is true, than the code will not work. But code is working only one time

    – MrLalatg
    Mar 22 at 18:46











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303114%2flistener-in-a-task-works-only-one-time%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Maybe you should try to make this function repeat itself by:



bool RunFlag = true // can be set to false somewhere else
public void DoListen()

while(RunFlag)
var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();







share|improve this answer























  • The problem is not in the class. Cuz' in the simple console application it works fine

    – MrLalatg
    Mar 22 at 18:27











  • At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

    – ElDuderino
    Mar 22 at 18:45











  • Cuz' if what he says is true, than the code will not work. But code is working only one time

    – MrLalatg
    Mar 22 at 18:46















0














Maybe you should try to make this function repeat itself by:



bool RunFlag = true // can be set to false somewhere else
public void DoListen()

while(RunFlag)
var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();







share|improve this answer























  • The problem is not in the class. Cuz' in the simple console application it works fine

    – MrLalatg
    Mar 22 at 18:27











  • At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

    – ElDuderino
    Mar 22 at 18:45











  • Cuz' if what he says is true, than the code will not work. But code is working only one time

    – MrLalatg
    Mar 22 at 18:46













0












0








0







Maybe you should try to make this function repeat itself by:



bool RunFlag = true // can be set to false somewhere else
public void DoListen()

while(RunFlag)
var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();







share|improve this answer













Maybe you should try to make this function repeat itself by:



bool RunFlag = true // can be set to false somewhere else
public void DoListen()

while(RunFlag)
var result =
DoRequest("GET", "https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling"); //&t=MYotE0N
var sid = ExtractToken(result);
if (string.IsNullOrEmpty(sid))

throw new Exception("Failed to get sid");


var cookie = new Cookie("io", sid, "/", "socket.donationalerts.ru");
DoRequest(
"POST",
$"https://socket.donationalerts.ru/socket.io/?EIO=3&transport=polling&sid=sid",
string.Format(addUserTemplate, _token),
cookie
);

var waiter = DoWebSocket($"wss://socket.donationalerts.ru/socket.io/?EIO=3&transport=websocket&sid=sid",
cookie);
waiter.GetAwaiter().GetResult();








share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 22 at 18:24









ElDuderinoElDuderino

334




334












  • The problem is not in the class. Cuz' in the simple console application it works fine

    – MrLalatg
    Mar 22 at 18:27











  • At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

    – ElDuderino
    Mar 22 at 18:45











  • Cuz' if what he says is true, than the code will not work. But code is working only one time

    – MrLalatg
    Mar 22 at 18:46

















  • The problem is not in the class. Cuz' in the simple console application it works fine

    – MrLalatg
    Mar 22 at 18:27











  • At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

    – ElDuderino
    Mar 22 at 18:45











  • Cuz' if what he says is true, than the code will not work. But code is working only one time

    – MrLalatg
    Mar 22 at 18:46
















The problem is not in the class. Cuz' in the simple console application it works fine

– MrLalatg
Mar 22 at 18:27





The problem is not in the class. Cuz' in the simple console application it works fine

– MrLalatg
Mar 22 at 18:27













At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

– ElDuderino
Mar 22 at 18:45





At the moment I do not see why Panagiotis Kanavos should be wrong with his comment.

– ElDuderino
Mar 22 at 18:45













Cuz' if what he says is true, than the code will not work. But code is working only one time

– MrLalatg
Mar 22 at 18:46





Cuz' if what he says is true, than the code will not work. But code is working only one time

– MrLalatg
Mar 22 at 18:46



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303114%2flistener-in-a-task-works-only-one-time%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript