private void OnTimerCallback(object state) { _timer.Change(Timeout.Infinite, Timeout.Infinite); try { var timeoutTime = DateTimeOffset.Now.AddSeconds(0 - _serverOptions.IdleSessionTimeOut); foreach (var s in _sessionContainer.GetSessions()) { if (s.LastActiveTime <= timeoutTime) { try { s.Channel.CloseAsync(); _logger.LogWarning($"Close the idle session {s.SessionID}, it's LastActiveTime is {s.LastActiveTime}."); } catch (Exception exc) { _logger.LogError(exc, $"Error happened when close the session {s.SessionID} for inactive for a while."); } } } } catch (Exception e) { _logger.LogError(e, "Error happened when clear idle session."); } _timer.Change(_serverOptions.ClearIdleSessionInterval * 1000, _serverOptions.ClearIdleSessionInterval * 1000); }
public async ValueTask ExecuteAsync(IAppSession session, PackageInfo package) { _sessionContainer = _serviceProvider.GetSessionContainer(); var sessions = _sessionContainer.GetSessions <ServerSession>(n => n.ClientType == ClientType.Web).ToList(); foreach (IAppSession serverSession in sessions) { await serverSession.SendAsync(Encoding.UTF8.GetBytes($"Output {package.Content}{Package.Terminator}")); } }
private async ValueTask <int> Push() { // about 300 characters var line = string.Join("-", Enumerable.Range(0, 10).Select(x => Guid.NewGuid().ToString())); var startTime = DateTime.Now; var count = 0; foreach (var s in _sessionContainer.GetSessions <PushSession>()) { await s.SendAsync(line); count++; if (_stopped) { break; } } return(count); }
public async ValueTask ExecuteAsync(IAppSession session, MQTTPacket package) { var pubpacket = package as PublishPacket; var sessions = sessionContainer.GetSessions <MQTTSession>(); var b = sessions.Where(x => x.TopicNames.Any(x => IsMatch(pubpacket.TopicName, x.TopicName))); await Task.Run(() => { foreach (var item in b) { item.SendAsync(pubpacket.TopicData); } }); }
public async ValueTask ExecuteAsync(IAppSession session, PackageInfo package) { var command = Command.Parser.ParseFrom(Encoding.UTF8.GetBytes(package.Content)); _sessionContainer = _serviceProvider.GetSessionContainer(); var sessions = _sessionContainer.GetSessions <ServerSession>(n => n.ClientType == ClientType.Agent && n.Ip == command.Ip).ToList(); foreach (IAppSession serverSession in sessions) { await serverSession.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Execute} {package.Content}{Package.Terminator}")); } await session.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Execute} Started{Package.Terminator}")); }
public async ValueTask ExecuteAsync(IAppSession session, PackageInfo package) { _sessionContainer = _serviceProvider.GetSessionContainer(); var sessions = _sessionContainer.GetSessions <ServerSession>(n => n.ClientType == ClientType.Agent).ToList(); var agents = sessions.Select(n => new AgentInfo { SessionId = n.SessionID, Ip = n.Ip, Port = n.Port, ConnectTime = n.ConnectTime }).ToList(); await session.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.ListAgent} {JsonConvert.SerializeObject(agents)}{Package.Terminator}")); }
public async ValueTask ExecuteAsync(IAppSession session, PackageInfo package) { Console.WriteLine(package.Content); _sessionContainer = _serviceProvider.GetSessionContainer(); var targetSession = _sessionContainer.GetSessions <ServerSession>(n => n.SessionID == package.Content).SingleOrDefault(); if (targetSession != null) { await targetSession.CloseAsync(); await session.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Disconnect} {package.Content} is disconnected{Package.Terminator}")); } else { await session.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Disconnect} {package.Content} is not found{Package.Terminator}")); } }
private async ValueTask Push() { if (_tcs != null) { await _tcs.Task; _tcs = null; } // about 300 characters var line = string.Join("-", Enumerable.Range(0, 10).Select(x => Guid.NewGuid().ToString())); var startTime = DateTime.Now; foreach (var s in _sessionContainer.GetSessions <PushSession>()) { await s.SendAsync(line); } _totalTimeSpent += DateTime.Now.Subtract(startTime).TotalMilliseconds; _totalRounds += 1; _total += line.Length; }
public IActionResult IndexAsync() { return(Ok(sessionContainer.GetSessions())); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>(args) .ConfigureSuperSocket(options => { options.AddListener(new ListenOptions { Ip = "Any", Port = 4040 }) .AddListener(new ListenOptions() { Ip = "Any", Port = 8888 }); }) .UseSession <MySession>() .UseSessionHandler(async s => { var data = new TcpPackage() { OpCode = OpCode.Connect, LocalName = "Server", RemoteName = "All", MessageType = MessageType.Text, Message = String.Empty, Clients = _clients }; var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { string da = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(da))); } }, async(s, e) => { _clients = _clients.Where(x => x.SessionId != s.SessionID).ToList(); var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); var data = new TcpPackage() { OpCode = OpCode.Connect, LocalName = "Server", RemoteName = "All", MessageType = MessageType.Text, Message = "Connect Success.", Clients = _clients.Count() == 1 ? null : _clients }; foreach (var session in sessions) { string val = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } }) .UsePackageHandler(async(s, p) => { var package = TcpPackage.JsonToPackage(p.Text); //Console.WriteLine($"\n{p.Text}\n"); switch (package.OpCode) { case OpCode.Connect: _clients.Add(new ClientInfo() { Username = package.LocalName, SessionId = s.SessionID }); var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { var connectData = new TcpPackage() { OpCode = OpCode.Connect, MessageType = MessageType.Text, LocalName = "Server", RemoteName = _clients.Where(x => s.SessionID == x.SessionId)?.FirstOrDefault() != null ? _clients.FirstOrDefault(x => s.SessionID == x.SessionId)?.Username : null, Message = "Connect Success.", Clients = _clients.Where(x => x.SessionId != session.SessionID).ToList() }; string conn = connectData.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(conn))); } break; case OpCode.All: TcpPackage allData = null; switch (package.MessageType) { case MessageType.Text: allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.Text, LocalName = package.LocalName, RemoteName = "All", Message = package.Message }; break; case MessageType.Image: //var imgConfig = new UdpConfigPackage() //{ // SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}|{11000}", // ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}|{12000}" //}; allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.Image, LocalName = "Server", RemoteName = package.LocalName, Config = null }; break; case MessageType.File: allData = new TcpPackage() { OpCode = OpCode.All, MessageType = MessageType.File, LocalName = "Server", RemoteName = package.LocalName, Message = s.LocalEndPoint.ToString() }; break; } var aSessionClients = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var sClient in aSessionClients) { string val = allData.ToString(); await sClient.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } break; case OpCode.Single: TcpPackage singleData = null; switch (package.MessageType) { case MessageType.Text: singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.Text, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = package.Message }; break; case MessageType.Image: //var imgConfig = new UdpConfigPackage() //{ // SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}.{11000}", // ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}.{12000}" //}; singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.Image, LocalName = "Server", RemoteName = package.LocalName, Message = null }; break; case MessageType.File: singleData = new TcpPackage() { OpCode = OpCode.Single, MessageType = MessageType.File, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = s.LocalEndPoint.ToString() }; break; } var remoteSession = _clients.Where(y => y.Username == package.RemoteName); foreach (var rSession in remoteSession) { var sSessionClients = _sessionContainer.GetSessions() .Where(x => x.SessionID.Equals(rSession.SessionId)); foreach (var sClient in sSessionClients) { var sing = singleData.ToString(); await sClient.SendAsync( new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(sing))); } } break; case OpCode.DisConnect: break; case OpCode.Confirm: var imgConfig = new UdpConfigPackage() { SendEndPoint = $"{((IPEndPoint)s.LocalEndPoint).Address}|{11000}", ReceiveEndPoint = $"{((IPEndPoint)s.RemoteEndPoint).Address}|{12000}" }; TcpPackage confirmPackage = new TcpPackage() { OpCode = OpCode.Confirm, MessageType = package.MessageType, LocalName = package.LocalName, RemoteName = package.RemoteName, Message = "image", Config = imgConfig }; #region 测试数据 //var testleData = new TcpPackage() //{ // OpCode = OpCode.Confirm, // MessageType = MessageType.Text, // LocalName = package.LocalName, // RemoteName = package.RemoteName, // Message = JsonConvert.SerializeObject(imgConfig), // Config = imgConfig //}; //var testString = testleData.ToString(); #endregion var confirmMsg = confirmPackage.ToString(); await s.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(confirmMsg))); if (package.RemoteName.Equals("All")) { confirmPackage.OpCode = OpCode.All; } else { confirmPackage.OpCode = OpCode.Single; } var cRemoteSession = _sessionContainer.GetSessions() .Where(x => x.SessionID != s.SessionID); var confirm = confirmPackage.ToString(); foreach (var session in cRemoteSession) { await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(confirm))); } break; default: throw new ArgumentException(message: "op code error"); } }) .ConfigureErrorHandler((s, v) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] Error信息:" + s.SessionID.ToString() + Environment.NewLine); return(default);
public ValueTask <IEnumerable <IAppSession> > GetSessionsAsync(Predicate <IAppSession> critera = null) { return(new ValueTask <IEnumerable <IAppSession> >(_syncSessionContainer.GetSessions(critera))); }
static async Task Main(string[] args) { var host = SuperSocketHostBuilder.Create <TextPackageInfo, LinePipelineFilter>(args) .ConfigureSuperSocket(options => { options.AddListener(new ListenOptions { Ip = "Any", Port = 4041 }) .AddListener(new ListenOptions() { Ip = "Any", Port = 8888 }); }) .UseSession <MySession>() .UseSessionHandler(onConnected: async(s) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] 客户端上线:" + ++_tcpCount + Environment.NewLine); var data = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", RemoteName = "All" }, Clients = _clients }; var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var session in sessions) { string da = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(da))); } }, onClosed: async(s, e) => { _clients = _clients.Where(x => x.SessionId != s.SessionID); var sessions = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); var data = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", TextMessage = "Connect Success." }, Clients = _clients.Count() == 1?null:_clients }; foreach (var session in sessions) { string val = data.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } Console.WriteLine($"\n[{DateTime.Now}] [TCP] 客户端下线:" + --_tcpCount + Environment.NewLine); }) .UsePackageHandler(async(s, p) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] 服务器信息:" + p.Text + Environment.NewLine); // Connect var package = JsonConvert.DeserializeObject <MessagePackage <TextMessageModel> >(p.Text); switch (package.OpCode) { case OpCode.Connect: _clients = _clients.Concat(new[] { new ClientInfo() { Username = package.Message.LocalName, SessionId = s.SessionID } }); var sessions = _sessionContainer.GetSessions(); foreach (var session in sessions) { var connectData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Connect, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = "Server", RemoteName = _clients.Where(x => s.SessionID == x.SessionId)?.FirstOrDefault().Username, TextMessage = "Connect Success." }, Clients = _clients.Where(x => x.SessionId != session.SessionID) }; string conn = connectData.ToString(); await session.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(conn))); } break; case OpCode.All: var allData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.All, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = package.Message.LocalName, RemoteName = "All", TextMessage = package.Message.TextMessage } }; var asessionClients = _sessionContainer.GetSessions().Where(x => x.SessionID != s.SessionID); foreach (var sClient in asessionClients) { string val = allData.ToString(); await sClient.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(val))); } break; case OpCode.Single: var singleData = new MessagePackage <TextMessageModel>() { OpCode = OpCode.Single, MessageType = MessageType.TextMessage, Message = new TextMessageModel() { LocalName = package.Message.LocalName, RemoteName = package.Message.RemoteName, TextMessage = package.Message.TextMessage } }; var remoteSession = _clients.Where(y => y.Username == package.Message.RemoteName); foreach (var rSession in remoteSession) { var ssessionClients = _sessionContainer.GetSessions() .Where(x => x.SessionID.Equals(rSession.SessionId)); foreach (var sClient in ssessionClients) { var sing = singleData.ToString(); await sClient.SendAsync( new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(sing))); } } break; case OpCode.Subscribe: default: throw new ArgumentException(message: "op code error"); } }) .ConfigureErrorHandler((s, v) => { Console.WriteLine($"\n[{DateTime.Now}] [TCP] Error信息:" + s.SessionID.ToString() + Environment.NewLine); return(default);