internal void AttachToSession(TcpMapServerSession session) { _attachedSession = session; _cts_wait_upgrade.Cancel(); }
async Task ProcessSocketAsync(Socket socket) { //LogMessage("new server conn : " + socket.LocalEndPoint + " , " + socket.RemoteEndPoint); string sessionid = Guid.NewGuid().ToString(); int tryagainIndex = 0; TryAgain: if (!socket.Connected) //this property is not OK .. actually the client has disconnect { return; } tryagainIndex++; if (tryagainIndex > 3) //only try 3 times. { return; } TcpMapServerClient sclient = FindClient(); if (sclient == null) { if (DateTime.Now - _lastDisconnectTime < TimeSpan.FromSeconds(8)) //TODO:const connect wait sclient timeout { await Task.Delay(500); goto TryAgain; } throw new Exception("no sclient."); } TcpMapServerClient presession = null; try { lock (_presessions) { if (_presessions.Count != 0) { presession = _presessions[0]; _presessions.RemoveAt(0); } } if (presession != null) { try { await presession.UpgradeSessionAsync(sessionid); } catch (Exception x) { OnError(x); LogMessage("Error:ServerWorker presession upgrade failed @" + tryagainIndex + " , " + sessionid); goto TryAgain; } lock (_sessions) _sessions.Add(presession); LogMessage("ServerWorker session upgraded @" + tryagainIndex + " , " + sessionid); } else { await sclient.StartSessionAsync(sessionid); LogMessage("ServerWorker session created @" + tryagainIndex + " , " + sessionid); } } catch (Exception x) { OnError(x); await Task.Delay(500); //TODO:const... goto TryAgain; } try { TcpMapServerSession session = new TcpMapServerSession(socket.CreateStream(), sessionid); sessionMap.TryAdd(sessionid, session); LogMessage("Warning: TcpMapServerSession added:" + sessionid); try { if (presession != null) { presession.AttachToSession(session); } await session.WorkAsync(); } finally { sessionMap.TryRemove(sessionid, out _); LogMessage("Warning: TcpMapServerSession removed:" + sessionid); } } catch (Exception x) { OnError(x); } await sclient.CloseSessionAsync(sessionid); //LogMessage("ServerWorker session closed @" + tryagainIndex); }