How to connect to Redis server using C#? - c#
I am only trying to test connection with the redis server? If all the connection configuration are correct and if I am able to establish a connection with the redis server using C#.
Here is the code that I used:
class Program
{
static readonly ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(
new ConfigurationOptions
{
EndPoints = { "******windows.net", "6380" },
Password = "****",
Ssl = true,
AbortOnConnectFail = false,
AllowAdmin = true,
ConnectTimeout = 30000,
SyncTimeout = 30000
});
static async Task Main(string[] args)
{
ThreadPool.SetMinThreads(10, 10);
var db = redis.GetDatabase();
var pong = await db.PingAsync();
Console.WriteLine(pong);
}
}
Here is the error I am getting:
StackExchange.Redis.RedisTimeoutException:
'The timeout was reached before the message could be written to the output buffer,
and it was not sent, command=PING,
timeout: 30000,
inst: 0,
qu: 0,
qs: 0,
aw: False,
bw: CheckingForTimeout,
rs: NotStarted,
ws: Initializing,
in: 0,
last-in: 0,
cur-in: 0,
serverEndpoint: 0.0.24.236:6380,
mc: 1/1/0,
mgr: 10 of 10 available,
clientName: SJAIN(SE.Redis-v2.6.80.25426),
IOCP: (Busy=0,Free=1000,Min=10,Max=1000),
WORKER: (Busy=2,Free=32765,Min=10,Max=32767),
POOL: (Threads=13,QueuedItems=0,CompletedItems=699),
v: 2.6.80.25426
(Please take a look at this article for some common client-side issues
that can cause timeouts:
https://stackexchange.github.io/StackExchange.Redis/Timeouts)'
What am I missing here with this code?
Here are complete logs:
11:20:43.7290: Connecting (sync) on .NET Core 3.1.31 (StackExchange.Redis: v2.6.80.25426)
11:20:43.8989: endpoint.windows.net,0.0.24.236,syncTimeout=30000,allowAdmin=True,connectTimeout=30000,password=*****,ssl=True,abortConnect=False
11:20:43.9637: endpoint.windows.net:6380/Interactive: Connecting...
11:20:44.0600: endpoint.windows.net:6380: BeginConnectAsync
11:20:44.1316: 0.0.24.236:6380/Interactive: Connecting...
11:20:44.1318: 0.0.24.236:6380: BeginConnectAsync
11:20:44.1503: 2 unique nodes specified (with tiebreaker)
11:20:44.1519: endpoint.windows.net:6380: OnConnectedAsync init (State=Connecting)
11:20:44.1521: 0.0.24.236:6380: OnConnectedAsync init (State=Connecting)
11:20:44.1538: Allowing 2 endpoint(s) 00:00:30 to respond...
11:20:44.2065: Awaiting 2 available task completion(s) for 30000ms, IOCP: (Busy=2,Free=998,Min=10,Max=1000), WORKER: (Busy=0,Free=32767,Min=10,Max=32767), POOL: (Threads=6,QueuedItems=0,CompletedItems=9)
11:20:44.4260: 0.0.24.236:6380: OnConnectedAsync completed (Disconnected)
11:20:44.5679: Connection failed: 0.0.24.236:6380 (Subscription, UnableToConnect): UnableToConnect on 0.0.24.236:6380/Subscription, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.6.80.25426
11:20:44.5679: Connection failed: 0.0.24.236:6380 (Interactive, UnableToConnect): UnableToConnect on 0.0.24.236:6380/Interactive, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.6.80.25426
11:20:44.5679: Connection failed: 0.0.24.236:6380 (Subscription, UnableToConnect): UnableToConnect on 0.0.24.236:6380/Subscription, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.6.80.25426
11:20:44.5679: Connection failed: 0.0.24.236:6380 (Interactive, UnableToConnect): UnableToConnect on 0.0.24.236:6380/Interactive, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.6.80.25426
11:20:47.5071: endpoint.windows.net:6380: OnConnectedAsync completed (Disconnected)
11:20:47.5183: Connection failed: endpoint.windows.net:6380 (Interactive, UnableToConnect): UnableToConnect on endpoint.windows.net:6380/Interactive, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 3s ago, last-write: 3s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 3s ago, v: 2.6.80.25426
11:20:47.5183: Connection failed: endpoint.windows.net:6380 (Subscription, UnableToConnect): UnableToConnect on endpoint.windows.net:6380/Subscription, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 3s ago, last-write: 3s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 3s ago, v: 2.6.80.25426
11:20:47.5427: All 2 available tasks completed cleanly, IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=3,Free=32764,Min=10,Max=32767), POOL: (Threads=13,QueuedItems=0,CompletedItems=29)
11:20:47.5559: Endpoint summary:
11:20:47.5571: endpoint.windows.net:6380: Endpoint is (Interactive: Connecting, Subscription: Connecting)
11:20:47.5571: 0.0.24.236:6380: Endpoint is (Interactive: Disconnected, Subscription: Disconnected)
11:20:47.5571: Task summary:
11:20:47.5574: endpoint.windows.net:6380: Returned, but incorrectly
11:20:47.5574: 0.0.24.236:6380: Returned, but incorrectly
11:20:47.5883: Election summary:
11:20:47.5955: Election: endpoint.windows.net:6380 had no tiebreaker set
11:20:47.5955: Election: 0.0.24.236:6380 had no tiebreaker set
11:20:47.5955: Election: No primaries detected
11:20:47.6068: Endpoint Summary:
11:20:47.6079: endpoint.windows.net:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Connecting; sub: Disconnected; not in use: DidNotRespond
11:20:47.6609: endpoint.windows.net:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=2; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=2
11:20:47.6626: endpoint.windows.net:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:20:47.6626: 0.0.24.236:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Disconnected; sub: Disconnected; not in use: DidNotRespond
11:20:47.6645: 0.0.24.236:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=2; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=2
11:20:47.6645: 0.0.24.236:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:20:47.6646: Sync timeouts: 0; async timeouts: 0; fire and forget: 0; last heartbeat: -1s ago
11:20:47.6648: Resetting failing connections to retry...
11:20:47.6765: Retrying - attempts left: 2...
11:20:47.6765: 2 unique nodes specified (with tiebreaker)
11:20:47.6766: endpoint.windows.net:6380: OnConnectedAsync init (State=Connecting)
11:20:47.6766: 0.0.24.236:6380: OnConnectedAsync init (State=Connecting)
11:20:47.6766: Allowing 2 endpoint(s) 00:00:30 to respond...
11:20:47.6906: Awaiting 2 available task completion(s) for 30000ms, IOCP: (Busy=1,Free=999,Min=10,Max=1000), WORKER: (Busy=4,Free=32763,Min=10,Max=32767), POOL: (Threads=13,QueuedItems=0,CompletedItems=35)
11:20:47.7117: 0.0.24.236:6380: OnConnectedAsync completed (Disconnected)
11:20:47.7527: endpoint.windows.net:6380: OnConnectedAsync completed (Disconnected)
11:20:47.7888: All 2 available tasks completed cleanly, IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=3,Free=32764,Min=10,Max=32767), POOL: (Threads=13,QueuedItems=0,CompletedItems=42)
11:20:47.7888: Endpoint summary:
11:20:47.7888: endpoint.windows.net:6380: Endpoint is (Interactive: Disconnected, Subscription: Disconnected)
11:20:47.7889: 0.0.24.236:6380: Endpoint is (Interactive: Disconnected, Subscription: Disconnected)
11:20:47.7889: Task summary:
11:20:47.7889: endpoint.windows.net:6380: Returned, but incorrectly
11:20:47.7889: 0.0.24.236:6380: Returned, but incorrectly
11:20:47.7889: Election summary:
11:20:47.7889: Election: endpoint.windows.net:6380 had no tiebreaker set
11:20:47.7889: Election: 0.0.24.236:6380 had no tiebreaker set
11:20:47.7889: Election: No primaries detected
11:20:47.7889: Endpoint Summary:
11:20:47.7889: endpoint.windows.net:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Disconnected; sub: Disconnected; not in use: DidNotRespond
11:20:47.7889: endpoint.windows.net:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=3; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=3
11:20:47.7890: endpoint.windows.net:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:20:47.7890: 0.0.24.236:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Disconnected; sub: Disconnected; not in use: DidNotRespond
11:20:47.7890: 0.0.24.236:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=3; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=3
11:20:47.7890: 0.0.24.236:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:20:47.7890: Sync timeouts: 0; async timeouts: 0; fire and forget: 0; last heartbeat: -1s ago
11:20:47.7890: Resetting failing connections to retry...
11:20:47.8632: Retrying - attempts left: 1...
11:20:47.8632: 2 unique nodes specified (with tiebreaker)
11:20:47.8632: endpoint.windows.net:6380: OnConnectedAsync init (State=Connecting)
11:20:47.8632: 0.0.24.236:6380: OnConnectedAsync init (State=Disconnected)
11:20:47.8632: Allowing 2 endpoint(s) 00:00:30 to respond...
11:20:47.9120: endpoint.windows.net:6380: OnConnectedAsync completed (Disconnected)
11:20:47.9120: Awaiting 2 available task completion(s) for 30000ms, IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=5,Free=32762,Min=10,Max=32767), POOL: (Threads=13,QueuedItems=0,CompletedItems=47)
11:21:17.8775: Not all available tasks completed cleanly (from ReconfigureAsync#1292, timeout 30000ms), IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=1,Free=32766,Min=10,Max=32767), POOL: (Threads=12,QueuedItems=0,CompletedItems=86)
11:21:17.8866: Server[0] (endpoint.windows.net:6380) Status: RanToCompletion (inst: 0, qs: 0, in: -1, qu: 0, aw: False, in-pipe: -1, out-pipe: -1, bw: Inactive, rs: NA. ws: NA)
11:21:17.8873: Server[1] (0.0.24.236:6380) Status: WaitingForActivation (inst: 0, qs: 0, in: -1, qu: 0, aw: False, in-pipe: -1, out-pipe: -1, bw: Inactive, rs: NA. ws: NA)
11:21:17.8873: Endpoint summary:
11:21:17.8873: endpoint.windows.net:6380: Endpoint is (Interactive: Disconnected, Subscription: Disconnected)
11:21:17.8873: 0.0.24.236:6380: Endpoint is (Interactive: Disconnected, Subscription: Disconnected)
11:21:17.8873: Task summary:
11:21:17.8873: endpoint.windows.net:6380: Returned, but incorrectly
11:21:17.8874: 0.0.24.236:6380: Did not respond (Task.Status: WaitingForActivation)
11:21:17.8874: Election summary:
11:21:17.8874: Election: endpoint.windows.net:6380 had no tiebreaker set
11:21:17.8874: Election: 0.0.24.236:6380 had no tiebreaker set
11:21:17.8875: Election: No primaries detected
11:21:17.8876: Endpoint Summary:
11:21:17.8885: endpoint.windows.net:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Disconnected; sub: Disconnected; not in use: DidNotRespond
11:21:17.8890: endpoint.windows.net:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=4; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=4
11:21:17.8897: endpoint.windows.net:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:21:17.8898: 0.0.24.236:6380: Standalone v4.0.0, primary; keep-alive: 00:01:00; int: Disconnected; sub: Disconnected; not in use: DidNotRespond
11:21:17.8898: 0.0.24.236:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=4; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=4
11:21:17.8898: 0.0.24.236:6380: Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s)
11:21:17.8898: Sync timeouts: 0; async timeouts: 0; fire and forget: 0; last heartbeat: -1s ago
11:21:17.8905: Starting heartbeat...
11:21:18.9710: 0.0.24.236:6380: OnConnectedAsync completed (Disconnected)
11:21:48.4544: Encountered exception: StackExchange.Redis.RedisTimeoutException: The timeout was reached before the message could be written to the output buffer, and it was not sent, command=SUBSCRIBE, timeout: 30000, inst: 0, qu: 0, qs: 0, aw: False, bw: CheckingForTimeout, last-in: 0, cur-in: 0, serverEndpoint: 0.0.24.236:6380, mc: 1/1/0, mgr: 10 of 10 available, clientName: SJAIN(SE.Redis-v2.6.80.25426), IOCP: (Busy=0,Free=1000,Min=10,Max=1000), WORKER: (Busy=0,Free=32767,Min=10,Max=32767), POOL: (Threads=14,QueuedItems=0,CompletedItems=294), v: 2.6.80.25426 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts)
at StackExchange.Redis.Maintenance.AzureMaintenanceEvent.AddListenerAsync(ConnectionMul
Updated Logs After Marc's answer
EndPoints = { "******windows.net", "6380" },
should be
EndPoints = { { "******windows.net", 6380 } },
or perhaps more simply:
EndPoints = { "******windows.net:6380" },
Right now, you're connecting to "******windows.net" on 6379, and (separately, as a different endpoint) "6380" on 6379.
Note that you will need to be able to reach the machine - it must resolve by DNS (or be specified as an IP address), be routable by you, and the designated port(s) must be open.
Related
Why my redis error is showing socketfailure error?
I have a project containing MVC and API. So right now my database is getting used every time when I reload page. So I am implementing Redis in both MVC and API. What I am doing is if the key is already present in redis than MVC will check it and fetch the data from there, and if not than it will send the request to API that will fetch the data from database and set it in Redis with a default time of 30 minutes. This is my Redis Class library: public class Redis{ static StreamWriter writer = new StreamWriter(#"C:\Temp\connectionLog.txt") static ConnectionMultiplexer redisConnection = ConnectionMultiplexer.Connect("connectionstring",writer); static readonly IDatabaseAsync dbConnection = redisConnection.GetDatabase(); public static async Task SetRecordAsync<T>(string recordId, T data, TimeSpan? timeSpan = null)//default 30 mins { var jsonData = JsonSerializer.Serialize(data); if (timeSpan.HasValue) { await dbConnection.StringSetAsync(recordId, jsonData, timeSpan); } else { timeSpan = TimeSpan.FromMinutes(30); await dbConnection.StringSetAsync(recordId, jsonData, timeSpan); } } public static async Task<T> GetValueAsync<T>(string recordId) { var data = await dbConnection.StringGetAsync(recordId); var jsonData = data.ToString(); if (jsonData is null) { return default(T); } return JsonSerializer.Deserialize<T>(jsonData); } public static async Task DeleteValueAsync(string recordId) { await dbConnection.KeyDeleteAsync(recordId); } public static async Task<bool> IsKeyNull(string recordId) { var value = await dbConnection.StringGetAsync(recordId); var isNull = value.IsNullOrEmpty ? true : false; return isNull; } } Whats confusing me is the fact that when I using the method IsKeyNull(This method returns true because initially no key is present and hence no value) from the redis classs library then code is working fine: //Code in API if (await Redis.IsKeyNull(Constant.RedisConstants.XYZ)) { var url = string.Format(ApiUrl.GetOnlineXYZCount, storeId); result = await HttpClientHelper.GetHttpResponseMessage(url); } else { result.StatusCode = HttpStatusCode.OK; result.Data = Redis.GetValueAsync<int>(Constant.RedisConstants.XYZ).GetAwaiter().GetResult(); } But when it gets true in above condition then API is called and this code is being run: //API if(Redis.IsKeyNull(Constants.RedisConstants.XYZ).GetAwaiter().GetResult()) { using (var uow = UnitOfWork) { var result = uow.Repository<Data.EntityFramework.Order>().Count(database query); Task task = Redis.SetRecordAsync<int>(Constants.RedisConstants.Order, result); task.Wait(); response.Result = result; } } Now the above code creates the problem, when the code hit Redis.IsKeyNull(Constants.RedisConstants.XYZ).GetAwaiter().GetResult(), an error is thrown: StackExchange.Redis.RedisConnectionException HResult=0x80131500 Message=No connection is active/available to service this operation: GET Order; A blocking operation was interrupted by a call to WSACancelBlockingCall, mc: 1/1/0, mgr: 10 of 10 available, clientName: ASR-PC, IOCP: (Busy=2,Free=998,Min=4,Max=1000), WORKER: (Busy=1,Free=8190,Min=4,Max=8191), v: 2.1x.58.3xyz Source=StackExchange.Redis StackTrace: at StackExchange.Redis.ConnectionMultiplexer.ThrowFailed[T](TaskCompletionSource`1 source, Exception unthrownException) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 2777 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at RedisCache.DistributedCacheExtensions.<IsKeyNull>d__4.MoveNext() in RedisCache\DistributedCacheExtensions.cs:line 67 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at BusinessLogic.Services.Order.OrderService.GetOnlineOrderCount(Int32 storeId) in OrderService.cs:line 1846 at GetOnlineOrderCount(Int32 storeId) in Api\Controllers\Order\OrderController.cs:line 443 at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) Inner Exception 1: RedisConnectionException: SocketFailure on windows.net:6380/Subscription, Initializing/NotStarted, last: NONE, origin: ConnectedAsync, outstanding: 0, last-read: 10s ago, last-write: 10s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 10s ago, v: 2.x.58.3xyz Inner Exception 2: IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. Inner Exception 3: SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall The log I received from my redis connectivity is this(connectionLog.txt): redis.redis.cache.windows.net:6380,syncTimeout=100000000,connectTimeout=100000000,password=*****,ssl=True,connectRetry=8 Connecting redis.cache.windows.net:6380/Interactive... BeginConnect: redis.cache.windows.net:6380 1 unique nodes specified Requesting tie-break from redis.cache.windows.net:6380 > __Booksleeve_TieBreak... Allowing endpoints 1.03:46:40 to respond... Awaiting task completion, IOCP: (Busy=0,Free=1000,Min=4,Max=1000), WORKER: (Busy=1,Free=8190,Min=4,Max=8191) Configuring TLS connection failed: redis.cache.windows.net:6380 (Subscription, SocketFailure): SocketFailure on redis.cache.windows.net:6380/Subscription, Initializing/NotStarted, last: NONE, origin: ConnectedAsync, outstanding: 0, last-read: 30s ago, last-write: 30s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 30s ago, v: 2.1.58.34321 > Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. > An existing connection was forcibly closed by the remote host connection failed: redis.cache.windows.net:6380 (Interactive, SocketFailure): SocketFailure on redis.cache.windows.net:6380/Interactive, Initializing/NotStarted, last: NONE, origin: ConnectedAsync, outstanding: 0, last-read: 30s ago, last-write: 30s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 30s ago, v: 2.1.58.34321 > Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. > An existing connection was forcibly closed by the remote host Finished awaiting tasks, IOCP: (Busy=0,Free=1000,Min=4,Max=1000), WORKER: (Busy=2,Free=8189,Min=4,Max=8191) redis.cache.windows.net:6380 faulted: SocketFailure on redis.cache.windows.net:6380/Interactive, Initializing/NotStarted, last: NONE, origin: ConnectedAsync, outstanding: 0, last-read: 30s ago, last-write: 30s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 30s ago, v: 2.1.58.34321 Waiting for tiebreakers... All tasks are already complete redis.cache.windows.net:6380 failed to nominate (Faulted) > SocketFailure on redis.cache.windows.net:6380/Interactive, Initializing/NotStarted, last: NONE, origin: ConnectedAsync, outstanding: 0, last-read: 30s ago, last-write: 30s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 30s ago, v: 2.1.58.34321 No masters detected redis.cache.windows.net:6380: Standalone v3.0.0, master; keep-alive: 00:01:00; int: Connecting; sub: Connecting; not in use: DidNotRespond redis.cache.windows.net:6380: int ops=0, qu=0, qs=0, qc=0, wr=0, socks=2; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=2 Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s; spans 10s) Sync timeouts: 0; async timeouts: 0; fire and forget: 0; last heartbeat: -1s ago resetting failing connections to retry... retrying; attempts left: 7... 1 unique nodes specified Requesting tie-break from redis.cache.windows.net:6380 > __Booksleeve_TieBreak... Allowing endpoints 1.03:46:40 to respond... Awaiting task completion, IOCP: (Busy=2,Free=998,Min=4,Max=1000), WORKER: (Busy=2,Free=8189,Min=4,Max=8191) Finished awaiting tasks, IOCP: (Busy=0,Free=1000,Min=4,Max=1000), WORKER: (Busy=2,Free=8189,Min=4,Max=8191) redis.cache.windows.net:6380 faulted: UnableToConnect on redis.cache.windows.net:6380/Interactive, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 30s ago, v: 2.1.58.34321 Waiting for tiebreakers... All tasks are already complete redis-red This is what my connection string looks like: windows.net:6380,password=xyz=,ssl=True,abortConnect=False,connectTimeout=10000,connectRetry=8,syncTimeout=3000
System.Timers.Timer sometimes stops and then resumes after a while
Let's have a class that every 5 seconds refreshes a key in Redis. (We call it "dead man switch"). The problem is, once per several days it just stops emitting the Elapsed event for a brief period of time, from seconds to 1-2 minutes. using System; using System.Timers; using Microsoft.Extensions.Logging; using StackExchange.Redis; namespace My { public class Test : IDisposable { private readonly ILogger<Test> _logger; private readonly IDatabase _redis; private readonly System.Timers.Timer _timer; public Test(ILogger<Test> logger, IDatabase redis) { _logger = logger; _redis = redis; _timer = new Timer {Interval = 5000}; _timer.Elapsed += Beat; _timer.Start(); } private void Beat(object sender, ElapsedEventArgs e) { _logger.LogInformation("Pushing DMS."); _redis.StringSet("1234", "OK", TimeSpan.FromSeconds(10), When.Always, CommandFlags.FireAndForget); _logger.LogInformation("DMS Pushed."); } public void Dispose() { Console.WriteLine("Disposing."); _timer?.Dispose(); } } } Log: ... [08:08:40 INF] Pushing DMS. [08:08:40 INF] DMS pushed. [08:08:45 INF] Pushing DMS. [08:08:45 INF] DMS pushed. [08:08:50 INF] Pushing DMS. [08:08:50 INF] DMS pushed. [08:09:17 INF] Pushing DMS. #<-- Here's a 27s gap [08:08:17 INF] DMS pushed. [08:08:23 INF] Pushing DMS. [08:08:23 INF] DMS pushed. ... These events do not queue up - it just creates a gap. This class is a part of bigger project running in a kubernetes cluster. I've googled up a theory that it can be caused by threadpool starvation so I added debug logging of threadpool state, but it IMO does not bring up any relevant information: private void Beat(object sender, ElapsedEventArgs e) { var ptc = Process.GetCurrentProcess().Threads.Count; ThreadPool.GetMaxThreads(out var maxWt, out var maxCpt); ThreadPool.GetAvailableThreads(out var wt, out var cpt); var current = ThreadPool.ThreadCount; var pending = ThreadPool.PendingWorkItemCount; var threadId = Thread.CurrentThread.ManagedThreadId; _logger.LogDebug( $"Pushing DMS.\nTP state: Thread#: {threadId} \t#Current: {current}\t #Pending: {pending}\t#WorkerT: {wt}/{maxWt}\t #CompletionT: {cpt}/{maxCpt}\n#ProcessT: {ptc}"); _redis.StringSet("1234", "OK", TimeSpan.FromSeconds(5), When.Always, CommandFlags.FireAndForget); _logger.LogInformation("DMS Pushed."); } Resulting log: [02:31:13 INF] Pushing DMS. TP state: Thread#: 92 #Current: 8 #Pending: 0 #WorkerT: 32760/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:31:13 INF] DMS Pushed. [02:31:18 INF] Pushing DMS. TP state: Thread#: 47 #Current: 11 #Pending: 0 #WorkerT: 32760/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:31:18 INF] DMS Pushed. [02:31:23 INF] Pushing DMS. TP state: Thread#: 47 #Current: 11 #Pending: 0 #WorkerT: 32761/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:31:23 INF] DMS Pushed. [02:31:28 INF] Pushing DMS. TP state: Thread#: 92 #Current: 8 #Pending: 0 #WorkerT: 32760/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:31:28 INF] DMS Pushed. # HERE COMES THE GAP [02:33:01 INF] Pushing DMS. TP state: Thread#: 103 #Current: 8 #Pending: 0 #WorkerT: 32760/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:33:01 INF] DMS Pushed. [02:33:06 INF] Pushing DMS. TP state: Thread#: 55 #Current: 10 #Pending: 0 #WorkerT: 32762/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:33:06 INF] DMS Pushed. [02:33:11 INF] Pushing DMS. TP state: Thread#: 103 #Current: 10 #Pending: 0 #WorkerT: 32762/32767 #CompletionT: 1000/1000 #ProcessT: 46 [02:33:11 INF] DMS Pushed. Does anyone have an idea what can cause this behavior?
getting stuck when started on editor with no any logs (perhaps because of time string parsing)
I'm making a 3D game on unity, and want to add the energy increasing functionality. I tried the below code which made my game stuck when trying to test on editor void Start() { // to calculate time since player left app to be used for energy increment currentTime = DateTime.Now.ToString(); lastTime = PlayerPrefs.GetString("lastTime", currentTime); if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { timeDT = Convert.ToDateTime(currentTime , null); CurrentTimeDT = Convert.ToDateTime(lastTime, null); timeSpan = timeDT.Subtract(CurrentTimeDT); timeDifference = int.Parse(timeSpan.TotalSeconds.ToString()); } else if (Application.platform == RuntimePlatform.WindowsEditor) { lastTime = lastTime.Substring(10); currentTime = currentTime.Substring(10); timeDT = DateTime.ParseExact(currentTime, "h:mm:ss tt" , null); CurrentTimeDT = DateTime.ParseExact(lastTime,"h:mm:ss tt", null); timeSpan = timeDT.Subtract(CurrentTimeDT); timeDifference = int.Parse(timeSpan.TotalSeconds.ToString()); } energy = PlayerPrefs.GetInt("energy", 5); //get last saved energy energy += Mathf.Abs(timeDifference / 300); //add one energy every 5 minutes since the player left app if (energy > 5) // the maximum energy amount { energy = 5; } I expected it to increase energy by 1 for each 5 minutes since the player left the game. But I got the unity program stuck with no any outputs. I tried building the game for android I got some logging from logcat. 08-21 04:15:52.153 1747-1760/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity bnds=[8,618][149,848]} from uid 1000 on display 0 08-21 04:15:52.153 1747-1760/? V/WindowManager: addAppToken: AppWindowToken{2efb58cd token=Token{24ade64 ActivityRecord{c6b2ff7 u0 com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity t39}}} to stack=1 task=39 at 0 08-21 04:15:52.157 2042-2042/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1341 android.content.ContextWrapper.sendBroadcast:382 com.vphone.launcher.Stats.recordLaunch:129 com.vphone.launcher.Launcher.c:3766 com.vphone.launcher.Launcher.onClickAppShortcut:3718 08-21 04:15:52.161 1747-1770/? V/WindowManager: Adding window Window{28d195fc u0 Starting com.Serv4Me.SlidingBall} at 3 of 6 (after Window{759b336 u0 com.vphone.launcher/com.vphone.launcher.Launcher}) 08-21 04:15:52.201 2042-2252/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.bindService:1770 android.content.ContextWrapper.bindService:539 com.google.android.gms.common.stats.zza.zza:-1 com.google.android.gms.common.stats.zza.zza:-1 com.google.android.gms.ads.identifier.AdvertisingIdClient.zzc:-1 --------- beginning of main 08-21 04:15:52.202 2042-2042/? D/yeshen: launcher onpause 08-21 04:15:52.231 1747-2657/? I/ActivityManager: Start proc 10837:com.Serv4Me.SlidingBall/u0a47 for activity com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity 08-21 04:15:52.242 10837-10837/? D/houdini: [10837] Initialize library(version: 5.0.7b_x.48396 RELEASE)... successfully. 08-21 04:15:52.543 10837-10837/? D/houdini: [10837] Added shared library /data/app/com.Serv4Me.SlidingBall-1/lib/arm/libmain.so for ClassLoader by Native Bridge. 08-21 04:15:52.619 1747-2032/? V/WindowManager: Adding window Window{5e10f3d u0 com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity} at 3 of 7 (before Window{28d195fc u0 Starting com.Serv4Me.SlidingBall}) 08-21 04:15:52.654 1747-1760/? V/WindowManager: Adding window Window{3ef00883 u0 SurfaceView} at 3 of 8 (before Window{5e10f3d u0 com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity}) 08-21 04:15:52.728 1747-1770/? I/ActivityManager: Displayed com.Serv4Me.SlidingBall/com.unity3d.player.UnityPlayerActivity: +526ms 08-21 04:15:52.728 1747-2034/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1327 com.android.server.InputMethodManagerService.hideCurrentInputLocked:1992 com.android.server.InputMethodManagerService.windowGainedFocus:2082 com.android.internal.view.IInputMethodManager$Stub.onTransact:221 com.android.server.InputMethodManagerService.onTransact:873 08-21 04:15:52.738 2042-2042/? D/yeshen: launcher onstop 08-21 04:15:52.738 2042-2042/? D/Tinker.DefaultAppLike: onTrimMemory level:20 08-21 04:15:52.741 2042-2277/? W/DebugConnManager: getNetworkInfo() on networkType 1 08-21 04:15:52.823 10837-10855/? I/Unity: SystemInfo CPU = ARMv7 VFPv3 NEON, Cores = 2, Memory = 2022mb 08-21 04:15:52.823 10837-10855/? I/Unity: SystemInfo ARM big.LITTLE configuration: 2 big (mask: 0x3), 0 little (mask: 0x0) 08-21 04:15:52.825 10837-10855/? I/Unity: ApplicationInfo com.Serv4Me.SlidingBall version 1.0 build 52251d08-2db4-4bc0-b627-11ed2dc44951 08-21 04:15:52.825 10837-10855/? I/Unity: Built from '2019.2/staging' branch, Version '2019.2.1f1 (ca4d5af0be6f)', Build type 'Release', Scripting Backend 'mono', CPU 'armeabi-v7a', Stripping 'Disabled' 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: [eglGetConfigAttrib] Bad attribute idx 12513 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: tid 10855: eglGetConfigAttrib(761): error 0x3004 (EGL_BAD_ATTRIBUTE) 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: [eglGetConfigAttrib] Bad attribute idx 12514 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: tid 10855: eglGetConfigAttrib(761): error 0x3004 (EGL_BAD_ATTRIBUTE) 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: [eglGetConfigAttrib] Bad attribute idx 1 08-21 04:15:53.267 10837-10855/? E/EGL_emulation: tid 10855: eglGetConfigAttrib(761): error 0x3004 (EGL_BAD_ATTRIBUTE) 08-21 04:15:53.307 10837-10855/? D/Unity: GL_EXT_debug_marker GL_OES_EGL_image GL_OES_EGL_image_external GL_OES_depth24 GL_OES_depth32 GL_OES_element_index_uint GL_OES_texture_float GL_OES_texture_float_linear GL_OES_compressed_paletted_texture GL_OES_compressed_ETC1_RGB8_texture GL_OES_depth_texture GL_EXT_texture_format_BGRA8888 GL_APPLE_texture_format_BGRA8888 GL_OES_texture_half_float GL_EXT_robustness GL_OES_texture_half_float_linear GL_OES_packed_depth_stencil GL_OES_vertex_half_float GL_OES_texture_npot GL_OES_rgb8_rgba8 GL_EXT_color_buffer_float ANDROID_gles_max_version_3_1 GL_OES_vertex_array_object 08-21 04:15:54.693 7816-7869/? E/PlayCommon: [290] afxf.d(308): Failed to connect to server for server timestamp: java.net.UnknownHostException: Unable to resolve host "play.googleapis.com": No address associated with hostname 08-21 04:15:54.753 2690-2690/? W/ChimeraUtils: Non Chimera context 08-21 04:15:54.845 7816-7869/? I/PlayCommon: [290] afxf.d(124): Connecting to server: https://play.googleapis.com/play/log?format=raw&proto_v2=true 08-21 04:15:54.847 7816-7869/? E/PlayCommon: [290] afxf.d(287): Failed to connect to server: java.net.UnknownHostException: Unable to resolve host "play.googleapis.com": No address associated with hostname 08-21 04:15:58.283 1747-1817/? D/ConnectivityService: releasing NetworkRequest NetworkRequest [ id=58, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED] ] 08-21 04:15:58.290 2042-2344/? D/ConnectivityManager.CallbackHandler: CM callback handler got msg 524296 08-21 04:15:58.902 1747-2032/? W/SensorService: sensor 00000000 already enabled in connection 0xa15fb460 (ignoring)
I solved the problem by deleting the PlayerPrefs from both the editor and android device which has the wrong datetime string parse. hope this helps someone else.
Network error handling for Android/Google Daydream (Unity)
Best way to create a UDP network for Android I recently asked a question regarding threading on Android (Google Daydream specific) which wasn't performing as expected. I was using a thread for communication to transfer information between an embedded system, and once the communication failed (i.e. the embedded system turned off, or any other 'can't transmit/receive' reason) the thread would abort and would attempt to reconnect to the embedded system until a connection is made again. This works perfectly running in Unity (5.6) on Windows, but once ported to Android the thread seems to just hang once the network goes down and won't acknowledge that the thread has died. The Update() function continues to loop, but it's not until I leave the scene that the thread dies and the code continues to perform as expected (see my other post here). I'm trying a new idea now where I'm assuming it's not the threading code which is problematic, or Android's inability to handle threads (as I've had no indication from anyone that what I'm doing can't be done on Android) but perhaps the handling of networks on Android or my UDP code. I've got my UDP code below and I wanted to see if anyone saw anything which immediately looks wrong: using UnityEngine; using System; using System.Net; using System.Net.Sockets; public class UDPConn : MonoBehaviour { Socket sock; IPEndPoint destEnd; IPEndPoint endPoint; EndPoint sender; // Bool for connection status public bool socketReady = false; // Receive timeout (ms). int rxTimeout = 1000; byte[] msg; // Try to initiate connection. public bool setupSocket(int conPort) { try { String hostName = ""; var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { hostName = ip.ToString(); } } System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(hostName); endPoint = new IPEndPoint(ipaddress, conPort); System.Net.IPAddress remoteIP = System.Net.IPAddress.Parse("192.168.20.2"); destEnd = new IPEndPoint(remoteIP, conPort); sender = (EndPoint)destEnd; sock = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); sock.Bind(endPoint); sock.ReceiveTimeout = rxTimeout; // Send message to 'wake' other side. sock.SendTo(System.Text.Encoding.ASCII.GetBytes("Connect"), sender); // Attempt to read from the socket. This will timeout if the other side isn't active. string readData = readSocket(); if (readData != null) { socketReady = true; return true; } else { socketReady = false; return false; } } catch (Exception e) { Debug.Log("Socket error: " + e); return false; } } // Send message to server. public void writeSocket(string theLine) { if (!socketReady) { return; } sock.SendTo(System.Text.Encoding.ASCII.GetBytes(theLine), sender); } // Read message from server. public string readSocket() { try { msg = new Byte[256]; sock.ReceiveFrom(msg, ref sender); String returnData = System.Text.Encoding.ASCII.GetString(msg); return returnData; } catch (Exception e) { Debug.Log("Socket error: " + e); return null; } } // Disconnect from the socket. public void closeSocket() { if (!socketReady) { return; } Debug.Log("UDPConn:closeSocket"); sock.Close(); socketReady = false; } } Other than my code, I also saved the Logcat (see end of post) at the point of where I disconnected the network from the Android phone (by swiping down from the screen, disabling the WiFi). My other idea outside of the UDP code is that perhaps I need to catch some sort of network error from Android and handle it better. The first item in Logcat is the last Debug.Log message I sent within Unity, and the first cnss-daemon message is the point at which I disconnected the network. Is there anything in there that can help identify my issue? Thanks very much for any help. Sorry for the long post. 06-30 14:07:56.150 19762 19966 I Unity : **Inside Thread Run() 06-30 14:07:56.150 19762 19966 I Unity : Stacktrace is not supported on this platform. 06-30 14:07:56.150 19762 19966 I Unity : (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51) 06-30 14:07:56.150 19762 19966 I Unity : 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:153): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:154): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:155): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:156): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:157): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:158): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability 06-30 14:07:56.153 1487 1487 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid=de:14:5c:9c:33:94 reason=3 locally_generated=1 06-30 14:07:56.154 1487 1487 W wpa_supplicant: nl80211: Was expecting local disconnect but got another disconnect event first 06-30 14:07:56.160 1110 1455 D WifiStateMachine: WifiStateMachine: Leaving Connected state 06-30 14:07:56.164 1110 1456 D DhcpClient: doQuit 06-30 14:07:56.170 1110 1456 D ApfFilter: (wlan0): shutting down 06-30 14:07:56.171 1110 1455 D WifiNative-HAL: stopRssiMonitoring, cmdId 0 06-30 14:07:56.174 1110 19709 D DhcpClient: Receive thread stopped 06-30 14:07:56.177 1110 1459 D ConnectivityService: NetworkAgentInfo [WIFI () - 110] EVENT_NETWORK_INFO_CHANGED, going from CONNECTED to DISCONNECTED 06-30 14:07:56.177 1110 1459 D ConnectivityService: NetworkAgentInfo [WIFI () - 110] got DISCONNECTED, was satisfying 8 06-30 14:07:56.177 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:56.189 639 1171 D CommandListener: Setting iface cfg 06-30 14:07:56.200 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:07:56.206 1110 19707 D DhcpClient: onQuitting 06-30 14:07:56.223 1682 1752 W QCNEJ : |CORE| network lost: 110 06-30 14:07:56.224 1682 1752 W QCNEJ : |CORE| onLost: unbind the process to WIFI 06-30 14:07:56.229 1487 1487 I wpa_supplicant: wlan0: CTRL-EVENT-REGDOM-CHANGE init=USER type=COUNTRY alpha2=US 06-30 14:07:56.238 639 1171 D CommandListener: Clearing all IP addresses on wlan0 06-30 14:07:56.244 1110 1455 D WifiCountryCode: Succeeded to set country code to: US 06-30 14:07:56.244 1110 1455 D WifiStateMachine: Start Disconnecting Watchdog 11 06-30 14:07:56.245 1110 1455 D WifiNative-HAL: stopRssiMonitoring, cmdId 0 06-30 14:07:56.256 1110 1455 I WifiConnectivityManager: scheduleWatchdogTimer 06-30 14:07:56.277 2037 2453 W Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value. 06-30 14:07:56.282 1110 1455 I WifiConnectivityManager: Set WiFi disabled 06-30 14:07:56.283 1110 1455 D WifiNetworkAgent: NetworkAgent: NetworkAgent channel lost 06-30 14:07:56.297 639 1171 V IdletimerController: runCmd(/system/bin/ip6tables -w -t raw -D idletimer_raw_PREROUTING -i wlan0 -j IDLETIMER --timeout 15 --label 1 --send_nl_msg 1) res_ipv4=0, res_ipv6=0 06-30 14:07:56.310 2037 2453 W Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value. 06-30 14:07:56.330 639 1171 V IdletimerController: runCmd(/system/bin/ip6tables -w -t mangle -D idletimer_mangle_POSTROUTING -o wlan0 -j IDLETIMER --timeout 15 --label 1 --send_nl_msg 1) res_ipv4=0, res_ipv6=0 06-30 14:07:56.332 1110 1459 D ConnectivityService: Sending DISCONNECTED broadcast for type 1 NetworkAgentInfo [WIFI () - 110] isDefaultNetwork=true 06-30 14:07:56.344 18824 18824 D MusicLifecycle: com.google.android.music.net.NetworkConnectivityMonitor$NetworkChangedReceiver generated event: Broadcast received with context com.google.android.music.ui.PhoneMusicApplication#e91968c and intent Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } 06-30 14:07:56.349 2393 18279 W MdnsClient_Cast: Multicast lock held. Releasing. Subtypes:"233637DE" 06-30 14:07:56.359 18824 18824 I NetworkConnectivity: Network state changed: null 06-30 14:07:56.372 2393 18279 W MdnsClient: unicast receiver thread is already dead. 06-30 14:07:56.384 18824 18824 I NetworkPolicyMonitor: Download-ability status changed to (false) unmetered wifi/eth: false mobileOrMetered: false 06-30 14:07:56.389 18824 18824 I NetworkPolicyMonitor: Stream-ability status changed to (false) unmetered wifi/eth: false mobileOrMetered: false 06-30 14:07:56.408 2393 18279 I DeviceScanner: [MDNS] notifyDevicesOffline: [] 06-30 14:07:56.422 2393 18279 E Publisher: ProcessDatabaseInternal start 06-30 14:07:56.424 2393 18279 I CastMediaRouteProvider: onDevicesPublished with 0 devices 06-30 14:07:56.438 2393 18279 I CastMediaRouteProvider: Published 0 routes 06-30 14:07:56.447 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:56.452 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:07:56.462 639 1171 E Netd : netlink response contains error (No such file or directory) 06-30 14:07:56.464 1110 1459 D NetworkNotificationManager: clearing notification tag=ConnectivityNotification:110 event=NO_INTERNET 06-30 14:07:56.490 2393 14149 W Herrevad: [660] rwh.b: Invalid mccmnc 06-30 14:07:56.495 2393 14149 W Herrevad: [660] rwh.b: Invalid mccmnc 06-30 14:07:56.525 18824 18935 W NetworkBandwidthMonitor: Unsuccessful attempt to get a Network Quality Client prediction (quality==null) 06-30 14:07:56.552 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:56.557 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:07:56.673 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:56.677 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:07:56.732 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:56.737 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:07:59.732 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:07:59.752 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:08:00.872 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:08:00.877 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:08:02.680 2164 2181 W GvrApi : GvrApi.shutdown() should be called to ensure resource cleanup 06-30 14:08:04.847 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:08:04.852 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl() 06-30 14:08:21.718 1110 1670 E : E/int izat_xtra::XtraDataRequest::doDownloadXtraData(const string &, string &):177][XTRA2] DNS resolution on xtrapath3.izatcloud.net failed. 06-30 14:08:24.766 2037 19816 W ctxmgr : [NetworkStateProducer]No state change for network connection context 06-30 14:08:26.012 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl() 06-30 14:08:26.017 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
GCM Pushing The Same Message Multiple Times (PushSharp)
Problem: I'm developing an android app with Xamarin that uses PushSharp. I am using GCM to send messages to the clients so I can update certain things if the app is open. GCM seems to be sending the same message to the same device multiple times. Logcat: Thread started: #12 09-17 08:40:34.307 I/PushSharp-GCM(20855): GCM Message Received! 09-17 08:40:34.317 V/GCMBaseIntentService(20855): Releasing Wakelock 09-17 08:40:34.327 V/UpdateSignalReceiver(20855): Message Receieved: ***** Thread finished: #12 The thread 'Unknown' (0xc) has exited with code 0 (0x0). 09-17 08:40:34.787 V/PushHandlerBroadcastReceiver(20855): OnReceive: com.google.android.c2dm.intent.RECEIVE 09-17 08:40:34.787 V/PushHandlerBroadcastReceiver(20855): GCM IntentService Class: rAMP_TabletV1.x5.GCMIntentService 09-17 08:40:34.787 V/GCMBaseIntentService(20855): Acquiring wakelock Thread started: #13 09-17 08:40:34.807 I/PushSharp-GCM(20855): GCM Message Received! 09-17 08:40:34.817 V/GCMBaseIntentService(20855): Releasing Wakelock 09-17 08:40:34.817 V/UpdateSignalReceiver(20855): Message Receieved: ***** Thread finished: #13 The thread 'Unknown' (0xd) has exited with code 0 (0x0). 09-17 08:40:35.817 V/PushHandlerBroadcastReceiver(20855): OnReceive: com.google.android.c2dm.intent.RECEIVE 09-17 08:40:35.817 V/PushHandlerBroadcastReceiver(20855): GCM IntentService Class: rAMP_TabletV1.x5.GCMIntentService 09-17 08:40:35.817 V/GCMBaseIntentService(20855): Acquiring wakelock Thread started: #14 09-17 08:40:35.857 I/PushSharp-GCM(20855): GCM Message Received! 09-17 08:40:35.857 V/GCMBaseIntentService(20855): Releasing Wakelock 09-17 08:40:35.867 V/UpdateSignalReceiver(20855): Message Receieved: ***** Thread finished: #14 The thread 'Unknown' (0xe) has exited with code 0 (0x0). 09-17 08:40:36.277 V/PushHandlerBroadcastReceiver(20855): OnReceive: com.google.android.c2dm.intent.RECEIVE 09-17 08:40:36.277 V/PushHandlerBroadcastReceiver(20855): GCM IntentService Class: rAMP_TabletV1.x5.GCMIntentService 09-17 08:40:36.277 V/GCMBaseIntentService(20855): Acquiring wakelock Thread started: #15 09-17 08:40:36.327 I/PushSharp-GCM(20855): GCM Message Received! 09-17 08:40:36.327 V/GCMBaseIntentService(20855): Releasing Wakelock 09-17 08:40:36.337 V/UpdateSignalReceiver(20855): Message Receieved: ***** Thread finished: #15 The thread 'Unknown' (0xf) has exited with code 0 (0x0). 09-17 08:40:36.717 V/PushHandlerBroadcastReceiver(20855): OnReceive: com.google.android.c2dm.intent.RECEIVE 09-17 08:40:36.717 V/PushHandlerBroadcastReceiver(20855): GCM IntentService Class: rAMP_TabletV1.x5.GCMIntentService 09-17 08:40:36.717 V/GCMBaseIntentService(20855): Acquiring wakelock Thread started: #16 09-17 08:40:36.747 I/PushSharp-GCM(20855): GCM Message Received! 09-17 08:40:36.757 V/GCMBaseIntentService(20855): Releasing Wakelock 09-17 08:40:36.757 V/UpdateSignalReceiver(20855): Message Receieved: ***** Sending the Message: Each device is registered and the registration id is stored in a database. I check the version number and the previous registration id to make sure that there are no duplicates, and also make sure I have the correct registration id. (I have double checked to make sure that there are no duplicates in my database) The update is called from a WCF service, and it will send the messages to all the registered devices. The method is only called once, and AllRegisteredDevices is a distinct list of device ids to send the message to. foreach (var deviceId in AllRegisteredDevices) { var webRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); webRequest.Method = "post"; webRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; webRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID)); webRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); var postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "®istration_id=" + deviceId + ""; Byte[] bytes = Encoding.UTF8.GetBytes(postData); webRequest.ContentLength = bytes.Length; var dataStream = webRequest.GetRequestStream(); dataStream.Write(bytes, 0, bytes.Length); dataStream.Close(); var webResponse = webRequest.GetResponse(); dataStream = webResponse.GetResponseStream(); var streamReader = new StreamReader(dataStream); var responseFromServer = streamReader.ReadToEnd(); streamReader.Close(); dataStream.Close(); webResponse.Close(); } // end loop Receiving The Message: I have a custom Broadcast Receiver to handle the message, depending on what the value of "message" is. The PushService passes it along to the receiver. Push Service protected override void OnMessage(Context context, Intent intent) { Log.Info(PushHandlerBroadcastReceiver.TAG, "GCM Message Received!"); string message = intent.Extras.GetString("message"); var theIntent = new Intent(UpdateAction); theIntent.PutExtra("message", message); SendOrderedBroadcast(theIntent, null); } // end OnMessage UpdateSignalReceiver [BroadcastReceiver] [IntentFilter(new string[]{PushHandlerService.UpdateAction}, Priority = (int)IntentFilterPriority.HighPriority)] public class UpdateSignalReceiver : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) { MyActivity TheActivity = ((MyActivity )context); string message = intent.Extras.GetString("message") ?? ""; Log.Verbose("UpdateSignalReceiver", "Message Receieved: " + message); if (message == "foo") { TheActivity.DoSomething(); } // end if else if (message == "bar") { TheActivity.SomethingElse(); } // end else if else { TheActivity.CatchAllMethod(); } // end else InvokeAbortBroadcast(); } // end on receieve } // end UpdateSignalReceiver Environment Samsung Galaxy Tab 3 Only factory installed apps (no other apps using the same GCM) Research: GCM Multiple Notifications - had to do with maintenance of the registered devices, which in my case they are all unique, no duplicates, and just to be sure, when populating my AllRegisteredDevices in the GCM call, I select distinct. GCM Duplicated Messages - GCM bug dating back to Feb, 2013. I doubt the bug is still in place, though it is possible. Question: Why am I receiving the same message repeatedly, when I'm only sending it once?
I have decided to go with a throttling approach. While this is not perfect in its implementation, the general idea is as follows: All Messages are given a Unique ID (Guid) The Broadcast Receiver has a static list of Guids containing the last 20 Message Ids we received and handled Only do work on messages that have an id not contained in our list, so we know it's a new message to this device. Limit the List to 20 IDs so it doesn't grow out of control. (20 seems to be more than enough, as repeat messages typically come in 3, sometimes 5 iterations) [BroadcastReceiver] [IntentFilter(new string[]{PushHandlerService.UpdateAction}, Priority = (int)IntentFilterPriority.HighPriority)] public class UpdateSignalReceiver : BroadcastReceiver { private static List<Guid> _Last20MessageIds; public override void OnReceive(Context context, Intent intent) { Guid MessageId; // Pull the MessageId from the intent String MessageIdString = intent.Extras.GetString("message_id" ?? Guid.Empty.ToString()); Guid.TryParse(MessageIdString, out MessageId); if (_Last20MessageIds == null) { _Last20MessageIds = new List<Guid>(); } // Make sure we didn't already receive this Message, then do work if (MessageId != null && MessageId != Guid.Empty && ! _Last20MessageIds.Contains(MessageId)) { DoSomeWorkWithIntent(intent); // Add the guid to the message id list _Last20MessageIds.Insert(0, MessageId); // Trim the list to the most recent 20 _Last20MessageIds= _Last20MessageIds.Take(20).ToList(); } InvokeAbortBroadcast(); } // end on receive } // end UpdateSignalReceiver