Skip to content

Commit

Permalink
used UDPClient and added OVERRIDE_TCP_KEEP_ALIVE by removing config key
Browse files Browse the repository at this point in the history
  • Loading branch information
budgetpreneur committed Nov 18, 2012
1 parent f8eef81 commit 5a1fead
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 116 deletions.
3 changes: 0 additions & 3 deletions csharp/3.3.0.1/PubNub-Messaging.Tests/App.config
Expand Up @@ -3,9 +3,6 @@
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup> </startup>
<appSettings>
<add key="OverrideTcpKeepAlive" value="false"/>
</appSettings>
<system.diagnostics> <system.diagnostics>
<trace autoflush="true" indentsize="4"> <trace autoflush="true" indentsize="4">
<listeners> <listeners>
Expand Down
1 change: 0 additions & 1 deletion csharp/3.3.0.1/PubNub-Messaging/PubNub-Messaging.csproj
Expand Up @@ -58,7 +58,6 @@
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" /> <Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.configuration" />
<Reference Include="System.Net" /> <Reference Include="System.Net" />
<Reference Include="System.XML" /> <Reference Include="System.XML" />
</ItemGroup> </ItemGroup>
Expand Down
136 changes: 27 additions & 109 deletions csharp/3.3.0.1/PubNub-Messaging/Pubnub.cs
Expand Up @@ -32,6 +32,7 @@ public class Pubnub : INotifyPropertyChanged
const int PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC = 15; const int PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC = 15;
const int PUBNUB_NETWORK_CHECK_RETRIES = 50; const int PUBNUB_NETWORK_CHECK_RETRIES = 50;
const int PUBNUB_WEBREQUEST_RETRY_INTERVAL_IN_SEC = 10; const int PUBNUB_WEBREQUEST_RETRY_INTERVAL_IN_SEC = 10;
const bool OVERRIDE_TCP_KEEP_ALIVE = false;


// Common property changed event // Common property changed event
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
Expand Down Expand Up @@ -74,8 +75,6 @@ public void RaisePropertyChanged(string propertyName)
// Timestamp // Timestamp
private List<object> _Time = new List<object>(); private List<object> _Time = new List<object>();


private bool _overrideTcpKeepAlive = false;

// Pubnub Core API implementation // Pubnub Core API implementation
private string ORIGIN = "pubsub.pubnub.com"; private string ORIGIN = "pubsub.pubnub.com";
private string PUBLISH_KEY = ""; private string PUBLISH_KEY = "";
Expand Down Expand Up @@ -110,8 +109,6 @@ private void init(string publish_key, string subscribe_key, string secret_key, s
else else
this.ORIGIN = "http://" + this.ORIGIN; this.ORIGIN = "http://" + this.ORIGIN;


_overrideTcpKeepAlive = Boolean.Parse(ConfigurationManager.AppSettings["OverrideTcpKeepAlive"].ToString());

//Initiate System Events for PowerModeChanged - to monitor suspend/resume //Initiate System Events for PowerModeChanged - to monitor suspend/resume
initiatePowerModeCheck(); initiatePowerModeCheck();
} }
Expand Down Expand Up @@ -232,14 +229,14 @@ void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{ {
_pubnetSystemActive = false; _pubnetSystemActive = false;
TerminatePendingWebRequest(); TerminatePendingWebRequest();
if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
heartBeatTimer.Change(Timeout.Infinite, Timeout.Infinite); heartBeatTimer.Change(Timeout.Infinite, Timeout.Infinite);
} }
if (appSwitch.TraceInfo) if (appSwitch.TraceInfo)
{ {
Trace.WriteLine(string.Format("DateTime {0}, System entered into Suspend Mode.", DateTime.Now.ToString())); Trace.WriteLine(string.Format("DateTime {0}, System entered into Suspend Mode.", DateTime.Now.ToString()));
if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
Trace.WriteLine(string.Format("DateTime {0}, Disabled Timer for heartbeat ", DateTime.Now.ToString())); Trace.WriteLine(string.Format("DateTime {0}, Disabled Timer for heartbeat ", DateTime.Now.ToString()));
} }
Expand All @@ -248,7 +245,7 @@ void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
else if (e.Mode == PowerModes.Resume) else if (e.Mode == PowerModes.Resume)
{ {
_pubnetSystemActive = true; _pubnetSystemActive = true;
if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
heartBeatTimer.Change( heartBeatTimer.Change(
(-1 == PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC) ? -1 : PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC * 1000, (-1 == PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC) ? -1 : PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC * 1000,
Expand All @@ -257,7 +254,7 @@ void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
if (appSwitch.TraceInfo) if (appSwitch.TraceInfo)
{ {
Trace.WriteLine(string.Format("DateTime {0}, System entered into Resume/Awake Mode.", DateTime.Now.ToString())); Trace.WriteLine(string.Format("DateTime {0}, System entered into Resume/Awake Mode.", DateTime.Now.ToString()));
if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
Trace.WriteLine(string.Format("DateTime {0}, Enabled Timer for heartbeat ", DateTime.Now.ToString())); Trace.WriteLine(string.Format("DateTime {0}, Enabled Timer for heartbeat ", DateTime.Now.ToString()));
} }
Expand Down Expand Up @@ -684,7 +681,7 @@ void OnPubnubWebRequestTimeout(object state, bool timeout)
} }
} }


if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
//reset heart beat time because http request already timedout //reset heart beat time because http request already timedout
heartBeatTimer.Change( heartBeatTimer.Change(
Expand Down Expand Up @@ -712,7 +709,7 @@ void OnPubnubHeartBeatTimeoutCallback(Object heartbeatState)


if (_channelInternetStatus.ContainsKey(currentState.channel) if (_channelInternetStatus.ContainsKey(currentState.channel)
&& (currentState.type == ResponseType.Subscribe || currentState.type == ResponseType.Presence) && (currentState.type == ResponseType.Subscribe || currentState.type == ResponseType.Presence)
&& _overrideTcpKeepAlive) && OVERRIDE_TCP_KEEP_ALIVE)
{ {
_channelInternetStatus[currentState.channel] = networkConnection; _channelInternetStatus[currentState.channel] = networkConnection;


Expand Down Expand Up @@ -917,7 +914,7 @@ private void _subscribe<T>(string channel, object timetoken, Action<T> usercallb
return; return;
} }


if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
if (appSwitch.TraceInfo) if (appSwitch.TraceInfo)
{ {
Expand Down Expand Up @@ -1042,7 +1039,7 @@ private void _presence<T>(string channel, object timetoken, Action<T> usercallba
return; return;
} }


if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
if (appSwitch.TraceInfo) if (appSwitch.TraceInfo)
{ {
Expand Down Expand Up @@ -1337,7 +1334,7 @@ private bool _urlRequest<T>(List<string> url_components, ResponseType type, Acti
_channelRequest.AddOrUpdate(channelName, pubnubRequestState, (key, oldState) => pubnubRequestState); _channelRequest.AddOrUpdate(channelName, pubnubRequestState, (key, oldState) => pubnubRequestState);
} }


if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
//Eventhough heart-beat is disabled, run one time to check internet connection by setting dueTime=0 //Eventhough heart-beat is disabled, run one time to check internet connection by setting dueTime=0
heartBeatTimer = new System.Threading.Timer( heartBeatTimer = new System.Threading.Timer(
Expand Down Expand Up @@ -1378,7 +1375,7 @@ private bool _urlRequest<T>(List<string> url_components, ResponseType type, Acti
string jsonString = streamReader.ReadToEnd(); string jsonString = streamReader.ReadToEnd();
streamReader.Close(); streamReader.Close();
if (_overrideTcpKeepAlive) if (OVERRIDE_TCP_KEEP_ALIVE)
{ {
heartBeatTimer.Change( heartBeatTimer.Change(
(-1 == PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC) ? -1 : PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC * 1000, (-1 == PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC) ? -1 : PUBNUB_NETWORK_TCP_CHECK_INTERVAL_IN_SEC * 1000,
Expand Down Expand Up @@ -1439,7 +1436,7 @@ private bool _urlRequest<T>(List<string> url_components, ResponseType type, Acti
|| webEx.Status == WebExceptionStatus.ConnectFailure //Sending Keep-alive packet failed (No network)/Server is down. || webEx.Status == WebExceptionStatus.ConnectFailure //Sending Keep-alive packet failed (No network)/Server is down.
|| webEx.Status == WebExceptionStatus.ServerProtocolViolation//Problem with proxy or ISP || webEx.Status == WebExceptionStatus.ServerProtocolViolation//Problem with proxy or ISP
|| webEx.Status == WebExceptionStatus.ProtocolError || webEx.Status == WebExceptionStatus.ProtocolError
) && (!_overrideTcpKeepAlive)) ) && (!OVERRIDE_TCP_KEEP_ALIVE))
{ {
//internet connection problem. //internet connection problem.
if (appSwitch.TraceError) if (appSwitch.TraceError)
Expand Down Expand Up @@ -2816,116 +2813,37 @@ private static void callbackClientNetworkStatus(bool status)


private static void checkClientNetworkAvailability(Action<bool> callback) private static void checkClientNetworkAvailability(Action<bool> callback)
{ {
#if (__MonoCS__) InternetState state = new InternetState();
bool connected = false; state.callback = callback;
if (NetworkInterface.GetIsNetworkAvailable()) ThreadPool.QueueUserWorkItem(checkSocketConnect, state);
{ mres.Wait();
Ping netMon = new Ping();

try
{
PingReply response = netMon.Send("pubsub.pubnub.com");
if (response != null)
{
if (appSwitch.TraceError)
{
Trace.WriteLine(response.RoundtripTime);
Trace.WriteLine(response.Status);
}
if(response.Status == IPStatus.Success)
{
connected = true;
}
}
}
catch (Exception ex)
{
if (appSwitch.TraceError)
{
Trace.WriteLine(string.Format("DateTime {0} checkSocketConnect Error. {1}", DateTime.Now.ToString(), ex.ToString()));
}
}
callback(connected);
}
else
{
callback(connected);
}
#else
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface netInterface in netInterfaces)
{
IPInterfaceProperties ip = netInterface.GetIPProperties();
if (netInterface.OperationalStatus == OperationalStatus.Up)
{
if (netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel
&& netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
IPInterfaceProperties prop = netInterface.GetIPProperties();
UnicastIPAddressInformationCollection unicast = prop.UnicastAddresses;

foreach (UnicastIPAddressInformation uniIP in unicast)
{
IPAddress addrip = uniIP.Address;
if (addrip.AddressFamily != AddressFamily.InterNetwork) continue;

InternetState state = new InternetState();
state.ipaddr = addrip;
state.callback = callback;
ThreadPool.QueueUserWorkItem(checkSocketConnect, state);
mres.Wait();
}
}
}
}
}
else
{
callback(false);
}
#endif
} }


private static void checkSocketConnect(object internetState) private static void checkSocketConnect(object internetState)
{ {
bool connected = false;
InternetState state = internetState as InternetState; InternetState state = internetState as InternetState;
IPAddress ipaddr = state.ipaddr;
Action<bool> callback = state.callback; Action<bool> callback = state.callback;
try try
{ {
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (UdpClient udp = new UdpClient("pubsub.pubnub.com", 80))
{ {
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); IPAddress localAddr = ((IPEndPoint)udp.Client.LocalEndPoint).Address;
udp.Close();


IPEndPoint local = new IPEndPoint(ipaddr, 0); if (appSwitch.TraceVerbose)
socket.Bind(local); {
socket.Connect("pubsub.pubnub.com", 80); Trace.WriteLine(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}", DateTime.Now.ToString(), localAddr.ToString()));
connected = true; }
socket.Shutdown(SocketShutdown.Both); callback(true);
socket.Disconnect(true);
socket.Close();
}
}
catch (ObjectDisposedException objEx)
{
if (appSwitch.TraceVerbose)
{
Trace.WriteLine(string.Format("DateTime {0} checkSocketConnect Error. {1}", DateTime.Now.ToString(), objEx.ToString()));
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
if (appSwitch.TraceVerbose) if (appSwitch.TraceError)
{ {
Trace.WriteLine(string.Format("DateTime {0} checkSocketConnect Error. {1}", DateTime.Now.ToString(), ex.ToString())); Trace.WriteLine(string.Format("DateTime {0} checkInternetStatus Error. {1}", DateTime.Now.ToString(), ex.ToString()));
} }
} callback(false);
if (callback != null)
{
callback(connected);
} }
mres.Set(); mres.Set();
} }
Expand Down
3 changes: 0 additions & 3 deletions csharp/3.3.0.1/PubNub-Messaging/app.config
Expand Up @@ -2,9 +2,6 @@
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
<appSettings>
<add key="OverrideTcpKeepAlive" value="false"/>
</appSettings>
<system.diagnostics> <system.diagnostics>
<trace autoflush="true" indentsize="4"> <trace autoflush="true" indentsize="4">
<listeners> <listeners>
Expand Down
Binary file modified csharp/3.3.0.1/PubNub.suo
Binary file not shown.

0 comments on commit 5a1fead

Please sign in to comment.