Skip to content

Instantly share code, notes, and snippets.

@guzba
Created August 2, 2019 02:45
Show Gist options
  • Save guzba/123f749ae8bf0dbbcfe1dbb0b8fcdadd to your computer and use it in GitHub Desktop.
Save guzba/123f749ae8bf0dbbcfe1dbb0b8fcdadd to your computer and use it in GitHub Desktop.
// Put this in app-wide initialization somewhere
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
public class Connection
{
private Thread thread;
private volatile bool listening;
private volatile int backoff;
private volatile Stream stream;
// Startup event / initialize connection thread
public void OnEvent(BootstrappedEvent e)
{
if (thread == null)
{
listening = true;
thread = new Thread(listen);
thread.IsBackground = true;
thread.Start();
}
}
// We're online
public void OnEvent(OnlineEvent e) {
backoff = Constants.DefaultBackoff;
if (thread != null)
{
thread.Interrupt();
}
}
// Signed out, shut things down
public void OnEvent(SignedOutEvent e)
{
if (thread != null)
{
listening = false;
if (stream != null)
{
stream.Close();
stream = null;
}
thread.Interrupt();
thread.Join();
thread = null;
}
}
private void listen()
{
backoff = Constants.DefaultBackoff;
while (listening)
{
var connected = false;
try
{
// Sleep backoff to not attempt reconnect immediately every time if server is down for some reason
Thread.Sleep(backoff);
L.WriteLine("Connecting to stream");
var request = (HttpWebRequest) WebRequest.Create("https://stream.pushbullet.com/streaming/" + PB.GetApiKey());
var response = request.GetResponse();
stream = response.GetResponseStream();
stream.ReadTimeout = 60 * 1000; // If we do not get a message within 60 seconds, the connection is dead and we need to reconnect (in this case, Exception will be thrown and backoff set then it'll retry)
using (var reader = new StreamReader(stream))
{
while (true)
{
var line = reader.ReadLine();
var data = JObject.Parse(line);
onMessage(data);
if (!connected)
{
connected = true;
EventBus.Post(new ConnectedEvent());
}
backoff = Constants.DefaultBackoff;
}
}
}
catch (Exception)
{
L.WriteLine("Error while listening on stream");
backoff = Math.Min(10 * 60 * 1000, backoff * 2);
}
}
}
private void onMessage(JObject data)
{
// We received a message (tickle, etc)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment