public static bool CheckStr(string name, ref string oldValue, string newValue, Device device) { if (newValue.IndexOf('<') != -1 || newValue.IndexOf('>') != -1 || (newValue.IndexOf('/') != -1 || newValue.IndexOf('"') != -1) || newValue.IndexOf('\'') != -1) { device.AddMessage(Message.ParameterError, name); return(false); } DataView dataView = ProtocolData.SelectFromDT("property='" + name + "'", device.IsNewVersion); if (dataView.Count == 0) { device.AddMessage(Message.ParameterError, name); return(false); } if (Encoding.UTF8.GetByteCount(newValue.Trim()) > (int)(sbyte)dataView[0]["maxLength"]) { device.AddMessage(Message.TooLong, name); return(false); } if (Encoding.UTF8.GetByteCount(newValue.Trim()) < (int)(sbyte)dataView[0]["minLength"]) { device.AddMessage(Message.TooShort, name); return(false); } oldValue = newValue.Trim(); return(true); }
public void SavePeerFile(string filePath, ProtocolData network) { if (network == null) { throw new ArgumentNullException(nameof(network)); } if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } MemoryStream ms = new MemoryStream(); CoinStream stream = new CoinStream(ms, true); stream.Type = SerializationType.Disk; stream.ReadWrite(network.Magic); stream.ReadWrite(this); var hash = Hashes.Hash256(ms.ToArray()); stream.ReadWrite(hash.AsCoinSerializable()); string dirPath = Path.GetDirectoryName(filePath); if (!string.IsNullOrWhiteSpace(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllBytes(filePath, ms.ToArray()); }
private void OnDeleteRole(object data) { ProtocolData pdata = data as ProtocolData; STC_DeleteRole stc_delete = pdata.MData as STC_DeleteRole; GameLog.Log(string.Format("delete Role:{0}", stc_delete.Res ? "ok" : "fail")); }
internal void DiscoverPeers(ProtocolData network, NodeConnectionParameters parameters) { if (Mode.HasFlag(AddressManagerBehaviorMode.Discover)) { AddressManager.DiscoverPeers(network, parameters, PeersToDiscover); } }
private void OnRegRole(object data) { ProtocolData pdata = data as ProtocolData; STC_CreateRegRole role = pdata.MData as STC_CreateRegRole; GameLog.Log(string.Format("注册:{0}", role.Res ? "ok" : "fail")); }
public static AddressManager LoadPeerFile(string filePath, ProtocolData expectedNetwork = null) { var addrman = new AddressManager(); byte[] data, hash; using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read)) { data = new byte[fs.Length - 32]; fs.Read(data, 0, data.Length); hash = new byte[32]; fs.Read(hash, 0, 32); } var actual = Hashes.Hash256(data); var expected = new uint256(hash); if (expected != actual) { throw new FormatException("Invalid address manager file"); } CoinStream stream = new CoinStream(data); stream.Type = SerializationType.Disk; uint magic = 0; stream.ReadWrite(ref magic); if (expectedNetwork != null && expectedNetwork.Magic != magic) { throw new FormatException("This file is not for the expected network"); } addrman.ReadWrite(stream); return(addrman); }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="stream">The stream.</param> /// <param name="data">The data.</param> /// <param name="final">if set to <c>true</c> than this frame is final for the stream.</param> /// <returns>returns DataFrame.</returns> public DataFrame BuildDataFrame(Http2Stream stream, ProtocolData data, bool final) { DataFrame frame = BuildDataFrame(stream.StreamId, data); frame.IsFinal = final; return(frame); }
private void OnGetUserInfo(object data) { ProtocolData pData = data as ProtocolData; STC_UserInfo userInfo = pData.MData as STC_UserInfo; GameLog.Log(string.Format("userId:{0} username:{1}", userInfo.MUserId, userInfo.MUserName)); }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="streamId">The stream id.</param> /// <param name="data">The data.</param> /// <returns>Returns DataFrame.</returns> public DataFrame BuildDataFrame(int streamId, ProtocolData data) { DataFrame frame = new DataFrame { Data = data.Data, StreamId = streamId, Length = data.Data.Length }; return(frame); }
private void OnLoginResult(ProtocolData data) { LoginProtocolData tdata = (LoginProtocolData)data; Debug.Log("LoginProtocol:userID=" + tdata.user.userID + ",userName="******",userPassword="******",photo=" + tdata.user.photo); }
private void GoOnRead(byte[] buffBytes, int remainLen) { MemoryStream readStream = new MemoryStream(); readStream.Write(buffBytes, 0, remainLen); readStream.Position = 0; BinaryReader breader = new BinaryReader(readStream); int totalLen = breader.ReadInt32(); //发生粘包 if (totalLen <= remainLen) { //协议id int protoId = breader.ReadInt32(); //协议体 byte[] protoBody = breader.ReadBytes(totalLen - sizeof(int) * 2); ServerLog.Log(string.Format("消息长度:{0}, 消息Id:{1}", totalLen, protoId)); Type protoType = ProtocolMgr.MInstance.GetTypeByProtoId((ProtocolEnum)protoId); if (protoType == null) { Console.WriteLine("No Such A Type Protocol Id : {0}", protoId); return; } using (MemoryStream pstream = new MemoryStream()) { pstream.Write(protoBody, 0, protoBody.Length); pstream.Position = 0; object obj = Serializer.NonGeneric.Deserialize(protoType, pstream); ProtocolData pData = ProtocolData.MakeProtocol((ProtocolEnum)protoId, obj, m_client.Client.RemoteEndPoint.ToString()); NetMsgDispatch.MInstance.DispathMsg((ProtocolEnum)protoId, pData); } //剩下的 int leftLen = remainLen - totalLen; ServerLog.Log(string.Format("还需读取:{0}", leftLen)); if (leftLen > 0) { byte[] remainBytes = breader.ReadBytes(leftLen); readStream.Close(); GoOnRead(remainBytes, leftLen); } else { KeepRead(); } } else { m_receiveOffSet = remainLen; KeepRead(); } }
private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Program.PATH = Application.StartupPath; ProtocolData.ReadXML(); Program.ReadMyShortcutKeys(); Program.mainForm = new MainForm(); Application.Run((Form)Program.mainForm); }
private void OnDeleteRole(object data) { ProtocolData pdata = data as ProtocolData; CTS_DeleteRole cts = pdata.MData as CTS_DeleteRole; bool res = UserMgr.MInstance.DeleteUserInfo(cts.MUserId);; STC_DeleteRole stc_update = new STC_DeleteRole(); stc_update.Res = res; ServerNet.MInstance.SendMsg(pdata.MIpEndPoint, STC_DeleteRole.MProtoId, stc_update); }
public static void AddOptionValue(int id, string value, IPAddress ipAddr, byte controlType) { OptionListClass optionListClass = (OptionListClass)null; OptionClass optionClass1 = (OptionClass)null; for (int index = 0; index < DataListManger.SendOList.Count; ++index) { if (DataListManger.SendOList[index].IpAddr == ipAddr && (int)DataListManger.SendOList[index].ControlType == (int)controlType) { optionListClass = DataListManger.SendOList[index]; using (List <OptionClass> .Enumerator enumerator = DataListManger.SendOList[index].OptionList.GetEnumerator()) { while (enumerator.MoveNext()) { OptionClass current = enumerator.Current; if ((int)current.OptionType == id) { optionClass1 = current; break; } } break; } } } if (optionListClass == null) { optionListClass = new OptionListClass(ipAddr, controlType); DataListManger.SendOList.Add(optionListClass); } if (optionClass1 == null) { DataView dataView = ProtocolData.SelectFromDT("code=" + (object)id, true); if (dataView.Count != 1) { return; } OptionClass optionClass2 = new OptionClass(dataView[0], Encoding.Default.GetBytes(value)); optionListClass.OptionList.Add(optionClass2); } else { if (!(value != "")) { return; } string s = Encoding.Default.GetString(optionClass1.OptionData) + value; optionClass1.OptionData = Encoding.Default.GetBytes(s); optionClass1.createOption(); } }
private void OnRegRole(object data) { ProtocolData pdata = data as ProtocolData; CTS_CreateRegRole roleInfo = pdata.MData as CTS_CreateRegRole; DBUserInfo info = DBUserInfo.CreateUserInfo(roleInfo); bool isOK = false; isOK = UserMgr.MInstance.AddUserInfo(info); STC_CreateRegRole stc_reg = new STC_CreateRegRole(); stc_reg.Res = isOK; ServerNet.MInstance.SendMsg(pdata.MIpEndPoint, STC_CreateRegRole.MProtoId, stc_reg); }
public void Dispatch(ProtocolEventType eventType, ProtocolData data) { Action <ProtocolData> protoEvent; eventDict.TryGetValue(eventType, out protoEvent); if (protoEvent != null) { Debug.Log("派发事件:" + eventType + "成功!"); protoEvent(data); } else { Debug.LogWarning("Event Dispatch失败, 事件系统没人监听该事件\nEventType=[" + eventType + "]"); } }
public VersionPayload CreateVersion(IPEndPoint peer, ProtocolData network) { VersionPayload version = new VersionPayload() { Nonce = Nonce == null?RandomUtils.GetUInt64() : Nonce.Value, UserAgent = UserAgent, Version = Version == null ? network.MaxP2PVersion : Version.Value, Timestamp = DateTimeOffset.UtcNow, AddressReceiver = peer, AddressFrom = AddressFrom ?? new IPEndPoint(IPAddress.Parse("0.0.0.0").MapToIPv6Ex(), network.DefaultPort), Relay = IsRelay, Services = Services }; return(version); }
private void CollectFromNamedChildren(ProfilerFrameData frameData, ProfilerSample sample) { if (!string.IsNullOrEmpty(sample.sampleName)) { string category = ProtocolData.GetCategory(frameData, unityVersion, sample.group); AddSampleData(sample.fullSampleName, sample.sampleName, category, sample.selfTimeUs / 1000.0f, sample.timeUS / 1000.0f); } if (sample.children != null) { foreach (var child in sample.children) { CollectFromNamedChildren(frameData, child); } } return; }
public override void SetupProtocolData() { if (ClientSource == null) { return; } ProtocolData = new ProtocolData { Business = ClientSource.BusinessName, DeviceNodeId = ClientSource.ClientNodeId, ProtocolContent = GetBytes(), ProtocolId = Guid.Parse(Protocol.GetIdString()), PackageDateTime = DateTime.Now, }; ProtocolData.Length = ProtocolData.ProtocolContent.Length; ProtocolData.ProtocolString = Encoding.ASCII.GetString(ProtocolData.ProtocolContent); }
private void AddAvailableProtocols() { // List <Assembly> UncompitbleTypes = ProtocolProvider.GetUncompitbleProtocolPlugIns(); if (UncompitbleTypes.Count > 0) { string Massege = string.Empty; foreach (Assembly A in UncompitbleTypes) { Massege += string.Format("The suplied dll {0} is not compatible with the current version, and was not loaded\n", A.GetName()); } MessageBox.Show(Massege, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); List <Type> ProtocolsData = ProtocolProvider.GetAvalbleProtocolPlugIns(); ToolStripItem[] ToolStripProtocols = new ToolStripItem[ProtocolsData.Count]; // remove all items but the first 3. (refresh btn etc..) int ProtocolsToolStripItemsCount = this.ProtocolsToolStrip.Items.Count; for (int i = ProtocolsToolStripItemsCount; i > 3; i--) { this.ProtocolsToolStrip.Items.RemoveAt(i - 1); } foreach (Type ProtocolData in ProtocolsData) { ToolStripButton BTN = new ToolStripButton( ((ProtocolAttribute)ProtocolData.GetCustomAttributes(typeof(ProtocolAttribute), true)[0]).ShortName, ((System.Drawing.Image)(resources.GetObject("Protocol1.Image")))); BTN.ImageTransparentColor = System.Drawing.Color.Magenta; BTN.Size = new System.Drawing.Size(88, 20); BTN.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; BTN.ToolTipText = ((ProtocolAttribute)ProtocolData.GetCustomAttributes(typeof(ProtocolAttribute), true)[0]).Description; BTN.Click += new System.EventHandler(this.AvailableProtocolClick); BTN.Tag = ProtocolData; this.ProtocolsToolStrip.Items.Add(BTN); } }
public OptionClass(string property, byte[] data, bool isNewVersion) { this.propertyName = property; this.optionData = data; DataView dataView = ProtocolData.Translation(this.propertyName, isNewVersion); if (dataView != null && dataView.Count > 0) { this.optionType = (ushort)dataView[0]["code"]; this.maxLength = (byte)((uint)Convert.ToByte(dataView[0]["maxLength"].ToString().Trim()) + 3U); this.dataType = dataView[0]["dataType"].ToString().Trim(); this.createOption(); } else { this.maxLength = (byte)0; } }
private void OnGetUserInfo(object data) { ProtocolData pdata = data as ProtocolData; CTS_GetUserInfo uinfo = pdata.MData as CTS_GetUserInfo; int uid = uinfo.MUserId; try { DBUserInfo info = UserMgr.MInstance.GetUserInfoById(uid); STC_UserInfo stc_userinfo = new STC_UserInfo(); stc_userinfo.MUserName = info.MUserName; ServerNet.MInstance.SendMsg(pdata.MIpEndPoint, STC_UserInfo.MProtoId, stc_userinfo); } catch (Exception exp) { ServerLog.Log(string.Format("{0}", exp.Message)); } }
private void OnUpdateRole(object data) { ProtocolData pdata = data as ProtocolData; CTS_UpdateRole cts_update = pdata.MData as CTS_UpdateRole; bool res = false; DBUserInfo uinfo = UserMgr.MInstance.GetUserInfoById(cts_update.MUserId); if (uinfo != null) { uinfo.MUserName = cts_update.MUserName; res = UserMgr.MInstance.UpdateUserInfo(uinfo); } STC_UpdateRole stc_update = new STC_UpdateRole(); stc_update.Res = res; ServerNet.MInstance.SendMsg(pdata.MIpEndPoint, STC_UpdateRole.MProtoId, stc_update); }
private void UpdateProtocolData(ProtocolData d) { if (d.TestRunning != isRunning) { ExecuteOnMainThread.AddAction(() => { StartStopTest(d.TestRunning); }); } float x = d.COGX * Current_Movement_Gain; float y = -d.COGY * Current_Movement_Gain; if (Math.Abs(x) < 0.003) { x = 0; } if (Math.Abs(y) < 0.003) { y = 0; } ExecuteOnMainThread.AddAction(() => { HandleBPCursor(x, y); }); if (swayAngleCount >= swayAngleCountNeeded) { float newSwayAngle = d.SwayAngle - swayAngleOffset; if (newSwayAngle != currentSwayAngle) { currentSwayAngle = newSwayAngle; ExecuteOnMainThread.AddAction(() => { SwayAngleChanged(); }); } } else { swayAngleSum += d.SwayAngle; ++swayAngleCount; if (swayAngleCount == swayAngleCountNeeded) { swayAngleOffset = swayAngleSum / (float)swayAngleCountNeeded; } } }
private void SetupCategories(ProfilerFrameData frameData) { if (this.categoryDictionary != null) { return; } this.categoriesStr = new List <string>(); this.categoryDictionary = new Dictionary <int, string>(); var categories = ProtocolData.GetCategories(frameData, this.unityVersion); foreach (var item in categories) { string name = item.Value.name; int idx = (int)item.Value.categoryId; if (!categoryDictionary.ContainsKey(idx)) { categoriesStr.Add(name); categoryDictionary.Add(idx, name); } } }
private void OnHeartBeating(object data) { ProtocolData pdata = data as ProtocolData; CTS_HeartBeating roleInfo = pdata.MData as CTS_HeartBeating; ServerClient client = ServerNet.MInstance.GetSClient(pdata.MIpEndPoint); if (client != null) { int seconds = (System.DateTime.Now - client.MLastBeatingTime).Seconds; if (seconds > m_timeSpace) { Console.WriteLine("连接超时"); } else { client.MLastBeatingTime = System.DateTime.Now; STC_HeartBeating stc_heart = new STC_HeartBeating(); client.SendMsg(STC_HeartBeating.MProtoId, stc_heart); } } }
/// <summary> /// Sends the data to the stream. /// </summary> /// <param name="data">The data.</param> /// <param name="isFin">if set to <c>true</c> than this stream will be half-closed.</param> public void SendData(ProtocolData data, bool isFin) { if (this.State == Http2StreamState.Opened) { ProtocolData dataFrame; if (Session.IsFlowControlEnabled) { //Session.CurrentWindowBalanceToServer -= data.Data.Length; dataFrame = new ProtocolData(data.Data); } else { dataFrame = new ProtocolData(data.Data); } this.protocol.SendData(this, dataFrame, isFin); } else { throw new InvalidOperationException("Trying to send data into closed stream!"); } }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="stream">The stream.</param> /// <param name="data">The data.</param> /// <returns>Returns DataFrame.</returns> public DataFrame BuildDataFrame(Http2Stream stream, ProtocolData data) { return(this.BuildDataFrame(stream, data, false)); }
/// <summary> /// Initializes a new instance of the <see cref="StreamDataEventArgs"/> class. /// </summary> /// <param name="stream">The stream.</param> /// <param name="data">The data.</param> /// <param name="isFin">final flag.</param> public StreamDataEventArgs(Http2Stream stream, ProtocolData data, bool isFin) : base(stream) { this.Data = data; this.IsFin = isFin; }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="stream">The stream.</param> /// <param name="data">The data.</param> /// <param name="final">if set to <c>true</c> than this frame is final for the stream.</param> /// <returns>returns DataFrame.</returns> public DataFrame BuildDataFrame(Http2Stream stream, ProtocolData data, bool final) { DataFrame frame = BuildDataFrame(stream.StreamId, data); frame.IsFinal = final; return frame; }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="streamId">The stream id.</param> /// <param name="data">The data.</param> /// <returns>Returns DataFrame.</returns> public DataFrame BuildDataFrame(int streamId, ProtocolData data) { DataFrame frame = new DataFrame { Data = data.Data, StreamId = streamId, Length = data.Data.Length }; return frame; }
public void RefreshOption(bool isNewVersion) { DataRowView dataRowView = (int)this.optionType < 179 || (int)this.optionType >= 184 ? ((int)this.optionType < 184 || (int)this.optionType >= 189 ? ProtocolData.Translation(this.optionType, isNewVersion) : ProtocolData.Translation((ushort)184, isNewVersion)) : ProtocolData.Translation((ushort)179, isNewVersion); this.propertyName = dataRowView["propertyName"].ToString().Trim(); this.dataType = dataRowView["dataType"].ToString().Trim(); this.maxLength = (byte)((uint)Convert.ToByte(dataRowView["maxLength"].ToString().Trim()) + 3U); }
/// <summary> /// Builds the data frame. /// </summary> /// <param name="stream">The stream.</param> /// <param name="data">The data.</param> /// <returns>Returns DataFrame.</returns> public DataFrame BuildDataFrame(Http2Stream stream, ProtocolData data) { return this.BuildDataFrame(stream, data, false); }
internal void DiscoverPeers(ProtocolData network, NodeConnectionParameters parameters, int peerToFind) { //TraceCorrelation traceCorrelation = new TraceCorrelation(NodeServerTrace.Trace, "Discovering nodes"); int found = 0; while (found < peerToFind) { parameters.ConnectCancellation.ThrowIfCancellationRequested(); //NodeServerTrace.PeerTableRemainingPeerToGet(-found + peerToFind); List <NetworkAddress> peers = new List <NetworkAddress>(); peers.AddRange(this.GetAddr()); CancellationTokenSource peerTableFull = new CancellationTokenSource(); CancellationToken loopCancel = CancellationTokenSource.CreateLinkedTokenSource(peerTableFull.Token, parameters.ConnectCancellation).Token; try { Parallel.ForEach(peers, new ParallelOptions() { MaxDegreeOfParallelism = 5, CancellationToken = loopCancel, }, p => { CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var cancelConnection = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, loopCancel); Node n = null; try { var param2 = parameters.Clone(); param2.ConnectCancellation = cancelConnection.Token; var addrman = param2.TemplateBehaviors.Find <AddressManagerBehavior>(); param2.TemplateBehaviors.Clear(); param2.TemplateBehaviors.Add(addrman); n = Node.Connect(network, p.Endpoint, param2); n.VersionHandshake(cancelConnection.Token); n.MessageReceived += (s, a) => { var addr = (a.Message.Payload as AddrPayload); if (addr != null) { Interlocked.Add(ref found, addr.Addresses.Length); if (found >= peerToFind) { peerTableFull.Cancel(); } } }; n.SendMessageAsync(new GetAddrPayload()); loopCancel.WaitHandle.WaitOne(2000); } catch { } finally { if (n != null) { n.DisconnectAsync(); } } if (found >= peerToFind) { peerTableFull.Cancel(); } //else // NodeServerTrace.Information("Need " + (-found + peerToFind) + " more peers"); }); } catch (OperationCanceledException) { if (parameters.ConnectCancellation.IsCancellationRequested) { throw; } } } }