private async Task <FileUploadFileStatus> AwaitOpenUploadFileStatus(string remoteFileName) { return(await Task.Run(() => { SendTo(CurrentSession, MessageHead.S_FILE_UPLOAD, new FileUploadPack() { FileName = remoteFileName }); //LogHelper.DebugWriteLog("get status"); if (_isWorkSessionOfLines) { var data = _workerStreamEvent.AwaitOneData(); if (data.IsNullOrEmpty()) { return null; } //LogHelper.DebugWriteLog("AwaitUploadFileStatus head:" + string.Join(",", data.Take(2).Select(c => c.ToString()).ToArray())); return PacketSerializeHelper.DeserializePacket <FileUploadFileStatus>(data); } else { return null; } })); }
private async Task <FileFristDownloadDataPack> AwaitOpenDownloadData(string remoteFileName, long position) { return(await Task.Run(() => { SendTo(CurrentSession, MessageHead.S_FILE_DOWNLOAD, new FileDownloadPack() { FileName = remoteFileName, Position = position }); if (_isWorkSessionOfLines)//判断是否离线,再进入阻塞等待 { var data = _workerStreamEvent.AwaitOneData(); if (data.IsNullOrEmpty()) { return null; } LogHelper.DebugWriteLog("AwaitFristDownloadData head:" + string.Join(",", data.Take(2).Select(c => c.ToString()).ToArray()) + " buffer lenght:" + data.Length); return PacketSerializeHelper.DeserializePacket <FileFristDownloadDataPack>(data); } else { return null; } })); }
private void ProcessLogin(SessionHandler session) { LoginPack login = PacketSerializeHelper.DeserializePacket <LoginPack>(session.CompletedBuffer.GetMessageBody()); session.AppTokens[2] = login.OpenScreenWall; if (this._manager_login_c == 0) { return; } LoginPackageModel login_model = new LoginPackageModel() { Msg = AJaxMsgCommand.S_SESSION_LOGIN, Id = (string)session.AppTokens[1], OS = login.OSVersion, MachineName = login.MachineName, Des = login.Remark, DesktopViewOpen = login.OpenScreenWall.ToString().ToLower() }; this.SendMessage(JsonConvert.SerializeObject(login_model)); }
public override void OnMessage() { var defineHeadSize = sizeof(int); if (ListByteBuffer.Count < defineHeadSize) { return; } byte[] lenBytes = ListByteBuffer.GetRange(0, defineHeadSize).ToArray(); int packageLen = BitConverter.ToInt32(lenBytes, 0); if (packageLen < 0 || packageLen > ApplicationConfiguartion.Options.MaxPacketSize || packageLen < 25) //数据不合法 或 小于大概ack固定长度 { this.Log(LogOutLevelType.Error, $"Type:{ConnectionWorkType.ToString()} 长度不合法!"); this.CloseSession(); return; } if (packageLen + defineHeadSize > ListByteBuffer.Count) { return; } this._ackRetainData = ListByteBuffer.GetRange(defineHeadSize, packageLen).ToArray(); ListByteBuffer.RemoveRange(0, packageLen + defineHeadSize); var longSize = sizeof(long); var packageBody = GZipHelper.Decompress(_ackRetainData, longSize, _ackRetainData.Length - longSize); var messageHead = TakeMessageHead(packageBody); if (messageHead == ACK_HEAD) { var ack = PacketSerializeHelper.DeserializePacket <AckPacket>(TakeMessage(packageBody)); this._accessId = ack.AccessId; if (ValidityAccessIdWithKey((ConnectionWorkType)ack.Type, ack.AccessId, ack.AccessKey)) { this.ApportionTypeHandlerEvent?.Invoke(this, (ConnectionWorkType)ack.Type); } else { if ((ConnectionWorkType)ack.Type == ConnectionWorkType.MainApplicationConnection) { var midData = MessageHelper.CopyMessageHeadTo(MessageHead.MID_ACCESS_KEY_WRONG); this.CurrentSession.SendAsync(midData.BuilderHeadPacket()); } this.Log(LogOutLevelType.Debug, $"Type:{((ConnectionWorkType)ack.Type).ToString()} AccessId:{ack.AccessId} 或AccessKey:{ack.AccessKey} 验证失败,登陆不成功!"); this.CloseSession(); } } else { this.CloseSession(); this.Log(LogOutLevelType.Warning, $"未知消息,连接被关闭!"); } }
static void Main(string[] args) { List <TestA> list = new List <TestA>(); for (int i = 0; i < 5; i++) { TestA a = new TestA() { Id = 12313213 + i, Ids = new int[] { 1213, 11, 1 }, Name = "哈哈哈", Names = new string[] { "嘿嘿", "AAA" }, B = new TestB() { isSuccess = true, Id = 12132132 + i, Data = new byte[] { 1, 2, 255 } }, As = new TestA[] { }, Time = DateTime.Now }; list.Add(a); } TestA A = new TestA() { Id = 123, Ids = null, Name = null, Names = null, B = null, As = list.ToArray(), //Time = DateTime.Now, MyEnum = MyEnum.B }; Stopwatch sw = new Stopwatch(); sw.Start(); var bytes = PacketSerializeHelper.SerializePacket(A); sw.Stop(); Console.WriteLine("序列化耗时:" + sw.Elapsed.TotalSeconds); sw.Reset(); sw.Start(); TestA pack = PacketSerializeHelper.DeserializePacket <TestA>(bytes); sw.Stop(); Console.WriteLine("反序列化耗时:" + sw.Elapsed.TotalSeconds); Console.Read(); }
public override void OnMessage() { var defineHeadSize = sizeof(int); if (ListByteBuffer.Count < defineHeadSize) { return; } byte[] lenBytes = ListByteBuffer.GetRange(0, defineHeadSize).ToArray(); int packageLen = BitConverter.ToInt32(lenBytes, 0); if (packageLen < 0 || packageLen > ApplicationConfiguartion.MaxPacketSize || packageLen < 25) //数据不合法 或 小于大概ack固定长度 { this.CloseSession(); return; } if (packageLen > ListByteBuffer.Count - defineHeadSize) { return; } this._ackRetainPacketData = ListByteBuffer.GetRange(0, defineHeadSize + packageLen).ToArray(); ListByteBuffer.RemoveRange(0, packageLen + defineHeadSize); this._accessId = BitConverter.ToInt64(_ackRetainPacketData, defineHeadSize); var longSize = sizeof(long); var packageBody = GZipHelper.Decompress(_ackRetainPacketData, defineHeadSize + longSize, _ackRetainPacketData.Length - defineHeadSize - longSize); var messageHead = TakeMessageHead(packageBody); if (messageHead == ACK_HEAD) { var ack = PacketSerializeHelper.DeserializePacket <AckPacket>(TakeMessage(packageBody)); if (ValidityAccessIdWithKey(ack.Type, ack.AccessId, ack.AccessKey)) { this.ApportionTypeHandlerEvent?.Invoke(this, ack.Type); } else { this.CloseSession(); } } else { this.CloseSession(); } }
private async Task <FileDownloadDataPack> AwaitDownloadDataPack() { return(await Task.Run(() => { SendTo(CurrentSession, MessageHead.S_FILE_NEXT_DATA); if (_isWorkSessionOfLines) { var data = _workerStreamEvent.AwaitOneData(); if (data.IsNullOrEmpty()) { return null; } //LogHelper.DebugWriteLog("AwaitDataPack head:" + string.Join(",", data.Take(2).Select(c => c.ToString()).ToArray()) + " buffer lenght:" + data.Length); return PacketSerializeHelper.DeserializePacket <FileDownloadDataPack>(data); } else { return null; } })); }
static void Main(string[] args) { if (args.Any(c => c.Equals(SERVICE_START, StringComparison.OrdinalIgnoreCase))) { ServiceBase.Run(new ServiceBase[] { new Service() }); } else//非服务启动 { var startParameter = new StartParameterEx() { Host = "94.191.115.121", //Port = 520, Port = 522, GroupName = "默认分组", RemarkInformation = "SiMayService", IsHide = false, IsMutex = false, IsAutoStart = false, //SessionMode = 0, SessionMode = 1, AccessKey = 5200, ServiceVersion = "正式6.0", RunTimeText = DateTime.Now.ToString(), UniqueId = "AAAAAAAAAAAAAAA11111111", ServiceName = "SiMayService", ServiceDisplayName = "SiMay远程被控服务", InstallService = false }; try { 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); var options = PacketSerializeHelper.DeserializePacket <ServiceOptions>(bytes); startParameter.Host = options.Host; startParameter.Port = options.Port; startParameter.RemarkInformation = options.Remark; startParameter.IsAutoStart = options.IsAutoRun; startParameter.IsHide = options.IsHide; startParameter.AccessKey = options.AccessKey; startParameter.SessionMode = options.SessionMode; startParameter.UniqueId = options.Id + $"_{Environment.MachineName}"; startParameter.IsMutex = options.IsMutex; startParameter.GroupName = options.GroupName; startParameter.InstallService = options.InstallService; startParameter.ServiceName = options.ServiceName; startParameter.ServiceDisplayName = options.ServiceDisplayName; } } catch { } if (startParameter.IsMutex) { //进程互斥体 bool bExist; Mutex mutex = new Mutex(true, startParameter.UniqueId + "_SiMayService", out bExist); if (!bExist) { Environment.Exit(0); } } AppConfiguartion.HasSystemAuthority = args.Any(c => c.Equals(SERVICE_USER_START, StringComparison.OrdinalIgnoreCase)); AppConfiguartion.ServiceName = startParameter.ServiceName.IsNullOrEmpty() ? "SiMayService" : startParameter.ServiceName; AppConfiguartion.ServiceDisplayName = startParameter.ServiceDisplayName.IsNullOrEmpty() ? "SiMay远程被控服务" : startParameter.ServiceDisplayName; //初始化连接服务 if (args.Any(c => c.Equals(SERVICE_USER_START, StringComparison.OrdinalIgnoreCase))) { LogHelper.DebugWriteLog("初始化连接服务"); new UserTrunkContext(args); } //非SYSTEM用户进程启动则进入安装服务 if (startParameter.InstallService && !args.Any(c => c.Equals(SERVICE_USER_START, StringComparison.OrdinalIgnoreCase))) { SystemSessionHelper.InstallAutoStartService(); } Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; try { new MainService.MainService(startParameter); } catch (Exception ex) { WriteException("main service exception!", ex); } SystemMessageNotify.InitializeNotifyIcon(); SystemMessageNotify.ShowTip("SiMay远程控制被控服务已启动!"); Application.Run(); } }
static void Main() { string remarkInfomation = "SiMayService";//初始化备注信息 bool isAutoStart = false; bool isHide = false; int sessionMode = 0; //服务器模式 //1是中间服务器模式 int accesskey = 5200; //初始连接密码 string id = "AAAAAAAAAAA11111111"; bool isMutex = false; try { 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); var options = PacketSerializeHelper.DeserializePacket <ServiceOptions>(bytes); string strlphost = options.Host; int lpport = options.Port; remarkInfomation = options.Remark; isAutoStart = options.IsAutoRun; isHide = options.IsHide; accesskey = options.AccessKey; sessionMode = options.SessionMode; id = options.Id; isMutex = options.IsMutex; while (true) //解析域名,直至解析成功 { ip = GetHostByName(strlphost); if (ip != null) { break; } Console.WriteLine(ip ?? "address analysis is null"); Thread.Sleep(5000); } port = lpport; } } catch { } if (isMutex) { //进程互斥体 bool bExist; Mutex MyMutex = new Mutex(true, "SiMayService", out bExist); if (!bExist) { Environment.Exit(0); } } Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; AppConfiguartion.ServerIPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); AppConfiguartion.AccessKey = accesskey; AppConfiguartion.DefaultRemarkInfo = remarkInfomation; AppConfiguartion.IsAutoRun = isAutoStart; AppConfiguartion.IsHideExcutingFile = isHide; AppConfiguartion.RunTime = DateTime.Now.ToString(); AppConfiguartion.Version = "正式-5.0"; AppConfiguartion.IsCentreServiceMode = sessionMode == 1 ? true : false; AppConfiguartion.IdentifyId = id; try { new MainService.MainService(); } catch (Exception ex) { WriteException("main service exception!", ex); } Application.Run(); }
private void ShowMessageBox(dynamic request) { string id = request.Id; string body = request.val; if (this._sessionDictionary.ContainsKey(id)) { MessagePack msg = new MessagePack(); msg.MessageIcon = (byte)MessageIcon.InforMation; msg.MessageTitle = "系统通知"; msg.MessageBody = body; byte[] data = MessageHelper.CopyMessageHeadTo(MessageHead.S_MAIN_MESSAGEBOX, PacketSerializeHelper.SerializePacket(msg)); this._sessionDictionary[id].SendAsync(data); } }
private void button3_Click(object sender, EventArgs e) { if (mls_address.Text.IsNullOrEmpty() || mls_port.Text.IsNullOrEmpty() || txtInitName.Text.IsNullOrEmpty() || txtAccesskey.Text.IsNullOrEmpty() || groupNameBox.Text.IsNullOrEmpty()) { MessageBoxHelper.ShowBoxExclamation("请输入完整正确的上线信息,否则可能造成上线失败!"); return; } if (groupNameBox.Text == "全部") { MessageBoxHelper.ShowBoxExclamation("分组名不能'全部'!"); return; } logList.Items.Clear(); logList.Items.Add("配置信息初始化.."); var autoRun = false; var svcInstall = false; if (installMode.SelectedIndex == 1) { autoRun = true; } else if (installMode.SelectedIndex == 2) { svcInstall = true; } var options = new ServiceOptions() { Id = Guid.NewGuid().ToString(), Host = mls_address.Text, Port = int.Parse(mls_port.Text), Remark = txtInitName.Text, AccessKey = int.Parse(txtAccesskey.Text), IsHide = ishide.Checked, IsAutoRun = autoRun, IsMutex = mutex.Checked, InstallService = svcInstall, ServiceName = "SiMayService", ServiceDisplayName = "SiMay远程被控服务", SessionMode = sessionModeList.SelectedIndex, GroupName = groupNameBox.Text }; string name = "SiMayService.exe"; string datfileName = Path.Combine(Environment.CurrentDirectory, "dat", name); logList.Items.Add("准备将配置信息写入文件中"); if (!File.Exists(datfileName)) { logList.Items.Add("配置文件不存在."); return; } SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "可执行文件|*.exe"; dlg.Title = "生成"; dlg.FileName = "SiMayService"; if (dlg.ShowDialog() != DialogResult.OK) { logList.Items.Add("配置信息写入被终止了!"); return; } if (dlg.FileName != "") { logList.Items.Add("配置信息写入中..."); var optionsBytes = PacketSerializeHelper.SerializePacket(options); bool err = this.WirteOptions(optionsBytes, datfileName, dlg.FileName); if (err != true) { logList.Items.Add("配置信息写入失败,请检查配置文件是否被占用!"); return; } logList.Items.Add("配置信息写入成功!"); } else { logList.Items.Add("配置信息写入被终止了!"); return; } MessageBoxHelper.ShowBoxExclamation("服务端文件已生成到位置:" + dlg.FileName); this.Close(); }
private void button3_Click(object sender, EventArgs e) { if (mls_address.Text == "" || mls_port.Text == "" || txtInitName.Text == "" || txtAccesskey.Text == "") { MessageBox.Show("请输入完整正确的上线信息,否则可能造成上线失败!", "提示", 0, MessageBoxIcon.Exclamation); return; } logList.Items.Clear(); logList.Items.Add("配置信息初始化.."); var options = new ServiceOptions() { Id = Guid.NewGuid().ToString(), Host = mls_address.Text, Port = int.Parse(mls_port.Text), Remark = txtInitName.Text, AccessKey = int.Parse(txtAccesskey.Text), IsHide = ishide.Checked, IsAutoRun = sutoRun.Checked, IsMutex = mutex.Checked, SessionMode = int.Parse(AppConfiguration.SessionMode) }; string name = "SiMayService.exe"; string datfileName = Application.StartupPath + "\\dat\\{0}".FormatTo(name); logList.Items.Add("准备将配置信息写入文件中"); if (!File.Exists(datfileName)) { logList.Items.Add("配置文件不存在."); return; } SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "可执行文件|*.exe"; dlg.Title = "生成"; dlg.FileName = "SiMayService"; if (dlg.ShowDialog() != DialogResult.OK) { logList.Items.Add("配置信息写入被终止了!"); return; } if (dlg.FileName != "") { logList.Items.Add("配置信息写入中..."); var optionsBytes = PacketSerializeHelper.SerializePacket(options); bool err = WirteOptions(optionsBytes, datfileName, dlg.FileName); if (err != true) { logList.Items.Add("配置信息写入失败,请检查配置文件是否被占用!"); return; } logList.Items.Add("配置信息写入成功!"); } else { logList.Items.Add("配置信息写入被终止了!"); return; } MessageBox.Show("服务端文件已生成到位置:" + dlg.FileName + "", "提示", 0, MessageBoxIcon.Exclamation); this.Close(); }