public override int GetHashCode() { int hash = 1; if (History != 0) { hash ^= History.GetHashCode(); } if (Depth != 0) { hash ^= Depth.GetHashCode(); } if (Mps != 0) { hash ^= Mps.GetHashCode(); } if (Reliability != 0) { hash ^= Reliability.GetHashCode(); } if (Durability != 0) { hash ^= Durability.GetHashCode(); } return(hash); }
public ActionResult Index() { Reliability world = new Reliability(); DataTable worldLocs = world.GetDataCenterLatLong(); world.ChangeDate(Convert.ToDateTime(Request.QueryString["start"]), Convert.ToDateTime(Request.QueryString["end"])); world.ChangePipeline(Request.QueryString["pipeline"]); var json = JsonConvert.SerializeObject(worldLocs); String[] dcs = world.GetAllDataCentersArray(); DataTable dcPipeAverage = new DataTable(); dcPipeAverage.Columns.Add("DataCenter", typeof(string)); dcPipeAverage.Columns.Add("Percent", typeof(decimal)); DataRow temp = dcPipeAverage.NewRow(); for (int i = 0; i < dcs.Length; i++) { world.ChangeDataCenter(dcs[i]); temp["DataCenter"] = dcs[i]; temp["Percent"] = world.CalculatePipeOverview(); dcPipeAverage.Rows.Add(temp); temp = dcPipeAverage.NewRow(); } var percentages = JsonConvert.SerializeObject(dcPipeAverage); ViewBag.AverageDCPercent = percentages; ViewBag.WorldMap = json; return(View()); }
/// <summary> /// Calculates the chance that the gun will jam /// </summary> /// <param name="verbEntry">The gun object</param> /// <returns>floating point number representing the jam chance</returns> public static float JamChance(Reliability verbEntry, Thing gun) { float result = 0f; switch (verbEntry) { case Reliability.UR: result = 50f; break; case Reliability.ST: result = 30f; break; case Reliability.VR: result = 10f; break; default: return(0); } if (gun != null) { result += GetQualityFactor(gun); result = result * 100 / gun.HitPoints / 100; } result = (float)(Math.Truncate((double)result * 100.0) / 100.0); return(result); }
public EncapsulatedPacket(Reliability reliability, uint messageId, byte[] payload) { Reliability = reliability; MessageId = messageId; Payload = payload; }
/// <summary> /// Sends a message to the user over the network. /// /// In general, the msg buffer does not need to live longer than the /// duration of the call. It's contents will be copied. /// </summary> /// <param name="msg">the buffer of the message</param> /// <param name="size">the size of the message, uses the size of the buffer if negative.</param> /// <param name="reliability">does the message need to be reliably sent</param> public void SendMessage(ReadOnlySpan <byte> msg, Reliability reliability = Reliability.Reliable) { if (MessageProcessor == null) { Lobby.SendNetworkMessage(Id, msg, reliability: reliability); _stats.BytesSent += (ulong)msg.Length; } else { int outputSize = msg.Length + 1; while (true) { Span <byte> output = stackalloc byte[outputSize]; if (!MessageProcessor.Apply(msg, ref output)) { outputSize *= 2; continue; } Lobby.SendNetworkMessage(Id, output, reliability: reliability); _stats.BytesSent += (ulong)msg.Length; break; } } _stats.PacketsSent++; }
public IList <PersonSourceDTO> GetPersonSourceDTOs(int personId) { PersonSourceDTO dto = null; PersonSource psAlias = null; Source sAlias = null; Person pAlias = null; Reliability rAlias = null; return(Session.QueryOver <PersonSource>(() => psAlias) .JoinAlias(() => psAlias.Source, () => sAlias) .JoinAlias(() => psAlias.Person, () => pAlias) .JoinAlias(() => psAlias.Reliability, () => rAlias) .Where(() => pAlias.Id == personId) .And(() => !psAlias.Archive) .SelectList(list => list .Select(() => psAlias.Id).WithAlias(() => dto.Id) .Select(() => psAlias.Commentary).WithAlias(() => dto.Commentary) .Select(() => psAlias.Notes).WithAlias(() => dto.Notes) .Select(() => sAlias.Id).WithAlias(() => dto.SourceId) .Select(() => sAlias.SourceName).WithAlias(() => dto.SourceName) .Select(() => sAlias.IsRestricted).WithAlias(() => dto.SourceIsRestricted) .Select(() => pAlias.Id).WithAlias(() => dto.PersonId) .Select(() => rAlias.Id).WithAlias(() => dto.ReliabilityId) .Select(() => rAlias.ReliabilityName).WithAlias(() => dto.ReliabilityName) ) .TransformUsing(Transformers.AliasToBean <PersonSourceDTO>()) .List <PersonSourceDTO>()); }
public void WriteToCustomPacket(CustomPacket packet) { byte flags = 0; flags |= (byte)((byte)Reliability << FLAG_RELIABILITY_INDEX); flags |= Split ? FLAG_SPLIT : (byte)0; packet.WriteByte(flags); packet.WriteUShort((ushort)(Payload.Length * 8)); if (Reliability.IsReliable()) { packet.WriteTriad(MessageIndex, ByteOrder.Little); } if (Reliability.IsOrdered() || Reliability.IsSequenced()) { packet.WriteTriad(OrderIndex, ByteOrder.Little); packet.WriteByte(OrderChannel); } if (Split) { packet.WriteInt(SplitCount); packet.WriteUShort(SplitId); packet.WriteInt(SplitIndex); } packet.WriteBytes(Payload); }
public EncapsulatedPacket(CustomPacket packet) { byte flags = packet.ReadByte(); Reliability = (Reliability)((flags & FLAG_RELIABILITY) >> FLAG_RELIABILITY_INDEX); Split = (flags & FLAG_SPLIT) > 0; int length = packet.ReadUShort() / 8; if (Reliability.IsReliable()) { MessageIndex = packet.ReadTriad(ByteOrder.Little); } if (Reliability.IsOrdered() || Reliability.IsSequenced()) { OrderIndex = packet.ReadTriad(ByteOrder.Little); OrderChannel = packet.ReadByte(); } if (Split) { SplitCount = packet.ReadInt(); SplitId = packet.ReadUShort(); SplitIndex = packet.ReadInt(); } Payload = packet.ReadBytes(length); }
public void AddEvent(IPeer peer, object data, Reliability reliability) { if (!isClosed) { eventPool.Enqueue(peer, data, reliability); } }
/// <summary> /// Broadcasts a network level message to all in the lobby. /// /// Note: this is (usually) different form sending a lobby message /// which is also broadcast to all other remote users in the lobby. /// /// In general, the msg buffer does not need to live longer than the /// duration of the call. It's contents will be copied. /// </summary> /// <param name="msg">the buffer of the message</param> /// <param name="reliability">does the message need to be reliably sent</param> public void Broadcast(Span <byte> msg, Reliability reliability = Reliability.Reliable) { foreach (var member in _members.Values) { member.SendMessage(msg, reliability: reliability); } }
public void ConnectWith(string hostName, Reliability requestedTransferReliability) { parent.ParallelStream.SetOnWriteToNull(); switch (requestedTransferReliability) { case Reliability.Reliable: string originalJoinedHostOnRemote = parent.onRemoteJoinedHostName.Value; parent.Write(new InternalMessage { MessageType = InternalMessageType.ConnectionRequest, Sender = parent.LocalHostName, Content = hostName }); parent.watcher.WaitForChange(parent.onRemoteJoinedHostName, originalJoinedHostOnRemote, parent.Dispose); break; case Reliability.Unreliable: if (!parent.EnableUnreliableTransfers) { throw new InvalidOperationException($"Unrelieble transfers have been disabled!"); } parent.onRemoteJoinedHostName.Value = hostName; parent.ParallelStream.OnWrite += parent.WriteDataUreliable; break; default: break; } TransferReliability = requestedTransferReliability; }
private async Task OnMessageReceivedAsync(IPEndPoint endPoint, byte[] data, Reliability reliability) { switch ((MessageIdentifier)data[0]) { case MessageIdentifier.ConnectionRequest: await DoConnectionRequestAsync(endPoint, data).ConfigureAwait(false); break; // These two (NewIncomingConnection, DisconnectionNotification) are not being sent by client for whatever reason case MessageIdentifier.NewIncomingConnection: if (ClientConnected != null) { await ClientConnected(endPoint).ConfigureAwait(false); } break; case MessageIdentifier.DisconnectionNotification: if (ClientDisconnected != null) { await ClientDisconnected(endPoint, CloseReason.ClientDisconnect).ConfigureAwait(false); } break; case MessageIdentifier.UserPacketEnum: if (MessageReceived != null) { await MessageReceived(endPoint, data, reliability); } break; } }
/// <summary> /// The raise generic event. /// </summary> /// <param name="itemId"> /// The item id. /// </param> /// <param name="itemType"> /// The item type. /// </param> /// <param name="customEventCode"> /// The custom event code. /// </param> /// <param name="eventData"> /// The event data. /// </param> /// <param name="eventReliability"> /// The event reliability. /// </param> /// <param name="eventReceiver"> /// The event receiver. /// </param> /// <returns> /// the OperationRequest /// </returns> public static OperationRequest RaiseGenericEvent( string itemId, byte?itemType, byte customEventCode, object eventData, Reliability eventReliability, EventReceiver eventReceiver) { var request = new OperationRequest { OperationCode = (byte)OperationCode.RaiseGenericEvent, Parameters = new Dictionary <byte, object>() }; request.Parameters.Add((byte)ParameterCode.CustomEventCode, customEventCode); if (eventData != null) { request.Parameters.Add((byte)ParameterCode.EventData, eventData); } request.Parameters.Add((byte)ParameterCode.EventReliability, (byte)eventReliability); request.Parameters.Add((byte)ParameterCode.EventReceiver, (byte)eventReceiver); if (itemId != null) { request.Parameters.Add((byte)ParameterCode.ItemId, itemId); } if (itemType.HasValue) { request.Parameters.Add((byte)ParameterCode.ItemType, itemType.Value); } return(request); }
void Analyze_reliability(List <Part> parts) { // reset data high_quality = 0.0; components = 0; failure_year = 0.0; redundancy = new Dictionary <string, int>(); // scan the parts double year_time = 60.0 * 60.0 * Lib.HoursInDay() * Lib.DaysInYear(); foreach (Part p in parts) { // for each module foreach (PartModule m in p.Modules) { // skip disabled modules if (!m.isEnabled) { continue; } // malfunctions if (m.moduleName == "Reliability") { Reliability reliability = m as Reliability; // calculate mtbf double mtbf = reliability.mtbf * (reliability.quality ? Settings.QualityScale : 1.0); // accumulate failures/y failure_year += year_time / mtbf; // accumulate high quality percentage high_quality += reliability.quality ? 1.0 : 0.0; // accumulate number of components ++components; // compile redundancy data if (reliability.redundancy.Length > 0) { int count = 0; if (redundancy.TryGetValue(reliability.redundancy, out count)) { redundancy[reliability.redundancy] = count + 1; } else { redundancy.Add(reliability.redundancy, 1); } } } } } // calculate high quality percentage high_quality /= Math.Max(components, 1u); }
public static bool IsReliable(this Reliability reliability) { return(reliability == Reliability.Reliable || reliability == Reliability.ReliableOrdered || reliability == Reliability.ReliableSequenced || reliability == Reliability.ReliableWithAckReceipt || reliability == Reliability.ReliableOrderedWithAckReceipt); }
public async Task SendAsync(int peerId, object obj, Reliability reliability) { GenericPacket packet = new GenericPacket(); packet.InstCode = OperationCode; packet.Data = obj; Task task = Task.Run(() => Send(peerId, packet, reliability)); await task; }
// // public Packet(byte[] raw):(byte[] raw, DateTime time // { // Packet(raw, DateTime.Now); // } public Packet(byte[] raw, DateTime time) { if (raw == null) { throw new ArgumentNullException(); } if (raw.Length < 20) { throw new ArgumentException(); } this.m_Raw = raw; this.m_Time = time; this.m_HeaderLength = (raw[0] & 0xF) * 4; if ((raw[0] & 0xF) < 5) { throw new ArgumentException(); } this.m_Precedence = (Precedence)((raw[1] & 0xE0) >> 5); this.m_Delay = (Delay)((raw[1] & 0x10) >> 4); this.m_Throughput = (Throughput)((raw[1] & 0x8) >> 3); this.m_Reliability = (Reliability)((raw[1] & 0x4) >> 2); this.m_TotalLength = raw[2] * 256 + raw[3]; if (!(this.m_TotalLength == raw.Length)) { throw new ArgumentException(); } // invalid size of packet; this.m_Identification = raw[4] * 256 + raw[5]; this.m_TimeToLive = raw[8]; m_Protocol = (InternetProtocol)raw[9]; m_Checksum = new byte[2]; m_Checksum[0] = raw[11]; m_Checksum[1] = raw[10]; try { m_SourceAddress = GetIPAddress(raw, 12); m_DestinationAddress = GetIPAddress(raw, 16); } catch (Exception e) { throw; } if (m_Protocol == InternetProtocol.Tcp || m_Protocol == InternetProtocol.Udp) { m_SourcePort = raw[m_HeaderLength] * 256 + raw[m_HeaderLength + 1]; m_DestinationPort = raw[m_HeaderLength + 2] * 256 + raw[m_HeaderLength + 3]; } else { m_SourcePort = -1; m_DestinationPort = -1; } }
public string getNetworkFarm() { Reliability test = new Reliability(); test.ChangeDataCenter(Request.QueryString["datacen"]); DataTable table = test.CalculateDataCenterHeatMap(); return(JsonConvert.SerializeObject(table, Formatting.Indented)); }
public ActionResult CompareDevice(List <string> devices, string startTime, string endTime) { var res = new JsonResult <List <CompareDeviceDto> >(); List <CompareDeviceDto> compareResult = new List <CompareDeviceDto>(); foreach (var dev in devices) { CompareDeviceDto dto = new CompareDeviceDto(); Expression <Func <Device, bool> > exp = item => item.DeviceNo == dev; DeviceDto devDto = Mapper.Map <Device, DeviceDto>(evaluateDAL.Single(exp)); dto.Device = devDto; MMDD_SBLY dncData = evaluateDAL.GetDncData(dev, startTime, endTime); DncRelated dncRelateReliability = Reliability.DncRelateReliability(dncData); dto.DncReliability = dncRelateReliability; //string mtbfSql = "select gzjgsj as jgsj from csmtbfsj"; //测试的时候用的,实际调用时应该给定sql语句 string recordsSql = "select app.DeviceNo,app.FailureType,app.BeginTime,app.FirstLocation,app.SecondLocation,app.ThirdLocation, round((" + "(case when app.CHECKTIME is null then to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss') else app.CHECKTIME end)-" + "(app.BEGINTIME)) * 24, 2) AS pausetime FROM REPAIRAPPLICATION app " + "WHERE (app.BEGINTIME > to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') AND app.BEGINTIME < to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss'))"; if (!String.IsNullOrEmpty(dev)) { recordsSql += " and app.DeviceNo='" + dev + "'"; } recordsSql += " order by app.begintime"; DataTable sourceTable = evaluateDAL.GetFailureRecords(recordsSql); List <double> intervar = new List <double>(); for (int i = 0; i < sourceTable.Rows.Count - 1; i++) { intervar.Add(Convert.ToDouble((Convert.ToDateTime(sourceTable.Rows[i + 1]["BeginTime"]) - Convert.ToDateTime(sourceTable.Rows[i]["BeginTime"])).TotalHours)); }//真实故障间隔数据 //intervar = evaluateDAL.Interval(mtbfSql); double alph, beta; dto.MTBF = Reliability.MTBF(intervar, out alph, out beta); dto.Alph = alph; dto.Beta = beta; string[] t = new string[2000]; double[] f = new double[2000]; Curve curve = new Curve(); for (int i = 1; i < 2000; i++) { t[i] = i.ToString(); f[i] = Math.Exp(-Math.Pow((i / alph), beta)); } curve.XValues = t; curve.YTimeValues = f; List <Curve> curves = new List <Curve>(); curves.Add(curve); dto.Curves = curves; compareResult.Add(dto); } res.data = compareResult; res.flag = true; return(Content(res.ToJsonString())); }
public MockTransport(string name, Dictionary<string, string> cap, Reliability reliability, Ordering ordering, uint maxPacketSize) { State = RunningState.Started; Name = name; Capabilities = cap; Reliability = reliability; Ordering = ordering; MaximumPacketSize = maxPacketSize; }
public void Send(int peerID, object obj, Reliability reliability) { if (peers.TryGetValue(peerID, out IPeer peer)) { GenericPacket packet = new GenericPacket(); packet.InstCode = OperationCode; packet.Data = obj; byte[] bytes = serializer.Serialize(packet); peer.Send(bytes, reliability); } }
protected override void OnReceivePacket(IPeer peer, object obj, Reliability reliability) { GenericPacket packet = obj as GenericPacket; if (packet != null) { if (groups.TryGetValue(packet.InstCode, out IPeerGroup group)) { group.AddEvent(peer, packet.Data, reliability); } } }
// // GET: /WorldMap/ public ActionResult Index() { Reliability world = new Reliability(); DataTable worldLocs = world.GetDataCenterLatLong(); var json = JsonConvert.SerializeObject(worldLocs); ViewBag.WorldMap = json; return(View()); }
public void SendData(int connectionId, byte[] data, Reliability reliability = Reliability.Unreliable) { IPEndPoint target = _connections[connectionId]; if (target == null) { // TODO Client not found return; } SendData(target, UdpCommand.Data, data, reliability); }
public void SendPacket(HighLevelPacket packet, Reliability reliability = Reliability.Reliable) { byte[] buf = packet.Encode(); EncapsulatedPacket encapsulatedPacket = new EncapsulatedPacket(reliability, SendMessageId++, buf); EncapsulatedPacket[] packets = encapsulatedPacket.GetSplitEncapsulatedPackets(SendSplitId++, MtuSize); for (int i = 0; i < packets.Length; i++) { SendDataPacket(packets[i].Encode()); } }
public void Broadcast(object obj, Reliability reliability) { GenericPacket packet = new GenericPacket(); packet.InstCode = OperationCode; packet.Data = obj; byte[] bytes = serializer.Serialize(packet); foreach (var peer in peers.Values) { peer.Send(bytes, reliability); } }
public Packet(byte[] raw, DateTime time) { if (raw == null) { throw new ArgumentNullException(); } if (raw.Length < 20) { throw new ArgumentException(); // invalid IP packet } m_Raw = raw; m_Time = time; m_Version = (raw[0] & 0xF0) >> 4; m_HeaderLength = (raw[0] & 0x0F) * 4 /* sizeof(int) */; if ((raw[0] & 0x0F) < 5) { throw new ArgumentException(); // invalid header of packet } m_Precedence = (Precedence)((raw[1] & 0xE0) >> 5); m_Delay = (Delay)((raw[1] & 0x10) >> 4); m_Throughput = (Throughput)((raw[1] & 0x8) >> 3); m_Reliability = (Reliability)((raw[1] & 0x4) >> 2); m_TotalLength = raw[2] * 256 + raw[3]; if (m_TotalLength != raw.Length) { throw new ArgumentException(); // invalid size of packet } m_Identification = raw[4] * 256 + raw[5]; m_TimeToLive = raw[8]; if (Enum.IsDefined(typeof(Protocol), (int)raw[9])) { m_Protocol = (Protocol)raw[9]; } else { m_Protocol = Protocol.Other; } m_Checksum = new byte[2]; m_Checksum[0] = raw[11]; m_Checksum[1] = raw[10]; m_SourceAddress = new IPAddress(BitConverter.ToUInt32(raw, 12)); m_DestinationAddress = new IPAddress(BitConverter.ToUInt32(raw, 16)); if (m_Protocol == Protocol.Tcp || m_Protocol == Protocol.Udp) { m_SourcePort = raw[m_HeaderLength] * 256 + raw[m_HeaderLength + 1]; m_DestinationPort = raw[m_HeaderLength + 2] * 256 + raw[m_HeaderLength + 3]; } else { m_SourcePort = -1; m_DestinationPort = -1; } }
public UdpPackage(UdpCommand command, Reliability reliability, ulong token, byte[] payload) { if (payload == null) { payload = new byte[0]; } Command = command; Reliability = reliability; ConfirmationToken = token; Payload = payload; Length = 1 + 1 + payload.Length + sizeof(ulong); }
public void Send(int operationCode, object data, Reliability reliability) { if (TryGetGroupId(operationCode, out int groupId)) { GenericPacket packet = new GenericPacket(); packet.InstCode = groupId; packet.Data = data; peer.Send(packet, reliability); } else { debugger.LogError("Cannot find group id."); } }
public ActionResult PercentData() { Reliability paramsPercent = new Reliability(Request.QueryString["datacen"], Convert.ToInt32(Request.QueryString["network"]), Convert.ToInt32(Request.QueryString["farm"]), Request.QueryString["pipeline"], Convert.ToDateTime(Request.QueryString["start"]), Convert.ToDateTime(Request.QueryString["end"])); DataTable percentTable = paramsPercent.PipelineGraphTable(Request.QueryString["pipeline"]); var json = JsonConvert.SerializeObject(percentTable, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); ViewBag.PercentData = json; return(View()); }
public static PacketEvent Create(IPeer peer, object data, Reliability reliability) { PacketEvent packet; if (stack.Count > 0) { packet = stack.Dequeue(); packet.Set(peer, data, reliability); } else { packet = new PacketEvent(peer, data, reliability); } return(packet); }
/// <summary> /// The try parse operation response. /// </summary> /// <param name = "data"> /// The data. /// </param> /// <param name = "reliability"> /// The reliability. /// </param> /// <param name = "channelId"> /// The channel id. /// </param> /// <param name = "operationResponse"> /// The operation response. /// </param> /// <returns> /// An exception. /// </returns> /// <exception cref = "NotSupportedException"> /// This method is not supported. /// </exception> public bool TryParseOperationResponse(byte[] data, Reliability reliability, byte channelId, out OperationResponse operationResponse) { throw new NotSupportedException(); }
public Packet(byte[] raw, DateTime time) { if (raw == null) throw new ArgumentNullException(); if (raw.Length < 20) throw new ArgumentException(); // invalid IP packet m_Raw = raw; m_Time = time; m_Version = (raw[0] & 0xF0) >> 4; m_HeaderLength = (raw[0] & 0x0F) * 4 /* sizeof(int) */; if ((raw[0] & 0x0F) < 5) throw new ArgumentException(); // invalid header of packet m_Precedence = (Precedence)((raw[1] & 0xE0) >> 5); m_Delay = (Delay)((raw[1] & 0x10) >> 4); m_Throughput = (Throughput)((raw[1] & 0x8) >> 3); m_Reliability = (Reliability)((raw[1] & 0x4) >> 2); m_TotalLength = raw[2] * 256 + raw[3]; if (m_TotalLength != raw.Length) throw new ArgumentException(); // invalid size of packet m_Identification = raw[4] * 256 + raw[5]; m_TimeToLive = raw[8]; if (Enum.IsDefined(typeof(Protocol), (int)raw[9])) m_Protocol = (Protocol)raw[9]; else m_Protocol = Protocol.Other; m_Checksum = new byte[2]; m_Checksum[0] = raw[11]; m_Checksum[1] = raw[10]; m_SourceAddress = new IPAddress(BitConverter.ToUInt32(raw, 12)); m_DestinationAddress = new IPAddress(BitConverter.ToUInt32(raw, 16)); if (m_Protocol == Protocol.Tcp || m_Protocol == Protocol.Udp) { m_SourcePort = raw[m_HeaderLength] * 256 + raw[m_HeaderLength + 1]; m_DestinationPort = raw[m_HeaderLength + 2] * 256 + raw[m_HeaderLength + 3]; } else { m_SourcePort = -1; m_DestinationPort = -1; } }
public void SendPackage(Player player, List<Package> messages, int mtuSize, ref int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { if (messages.Count == 0) return; PlayerNetworkSession session; if (_playerSessions.TryGetValue(player.EndPoint, out session)) { Datagram.CreateDatagrams(messages, mtuSize, ref reliableMessageNumber, session, SendDatagram); foreach (var message in messages) { Thread.Sleep(1); // Seems to be needed regardless :-( if (message is InternalPing) { ServerInfo.Latency = (ServerInfo.Latency*9 + message.Timer.ElapsedMilliseconds)/10; } TraceSend(message); message.PutPool(); } } }
public void SendPackage(Player player, List<Package> messages, int mtuSize, ref int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { if (messages.Count == 0) return; Datagram.CreateDatagrams(messages, mtuSize, ref reliableMessageNumber, player.EndPoint, SendDatagram); foreach (var message in messages) { if (!player.IsBot) Thread.Sleep(5); if (message is InternalPing) { _latency = (_latency*9 + message.Timer.ElapsedMilliseconds)/10; } TraceSend(message); message.PutPool(); } }
/// <summary> /// A constructor for specifying the most common requirements. /// </summary> /// <param name="d">the minimum reliability requirement</param> /// <param name="a">the minimum aggregation requirement</param> /// <param name="o">the minimum ordering requirement</param> public MessageDeliveryRequirements(Reliability d, MessageAggregation a, Ordering o) { Reliability = d; Aggregation = a; Ordering = o; }
public ReliabilityWrapper(Reliability item) { this.Item = item; }
public void SendPackage(IPEndPoint senderEndpoint, List<Package> messages, short mtuSize, ref int datagramSequenceNumber, ref int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { if (messages.Count == 0) return; foreach (var message in messages) { TraceSend(message); } Datagram.CreateDatagrams(messages, mtuSize, ref reliableMessageNumber, senderEndpoint, SendDatagram); }
public void SendPackage(Player player, Package message, int mtuSize, Reliability reliability = Reliability.Reliable) { if (message == null) return; PlayerNetworkSession session; if (_playerSessions.TryGetValue(player.EndPoint, out session)) { foreach (var datagram in Datagram.CreateDatagrams(message, mtuSize, session)) { SendDatagram(session, datagram); } TraceSend(message); message.PutPool(); //Thread.Sleep(1); // Really important to slow down speed a bit } }
public int SendPackage(Package message, short mtuSize, int sequenceNumber, int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { byte[] encodedMessage = message.Encode(); //int count = (int) Math.Ceiling(encodedMessage.Length/((double) mtuSize - 60)); int count = 1; int index = 0; short splitId = (short) (sequenceNumber%65536); //foreach (var bytes in ArraySplit(encodedMessage, mtuSize - 60)) //{ ConnectedPackage package = new ConnectedPackage { Buffer = encodedMessage, _reliability = reliability, _reliableMessageNumber = reliableMessageNumber++, _datagramSequenceNumber = sequenceNumber++, _hasSplit = count > 1, _splitPacketCount = count, _splitPacketId = splitId, _splitPacketIndex = index++ }; byte[] data = package.Encode(); SendData(data); //} message.PutPool(); return count; }
/// <summary> /// The raise generic event. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="itemId"> /// The item id. /// </param> /// <param name="itemType"> /// The item type. /// </param> /// <param name="customEventCode"> /// The custom event code. /// </param> /// <param name="eventData"> /// The event data. /// </param> /// <param name="eventReliability"> /// The event reliability. /// </param> /// <param name="eventReceiver"> /// The event receiver. /// </param> public static void RaiseGenericEvent( Client client, string itemId, byte? itemType, byte customEventCode, object eventData, Reliability eventReliability, EventReceiver eventReceiver) { var data = new Dictionary<byte, object> { { (byte)ParameterCode.CustomEventCode, customEventCode }, { (byte)ParameterCode.EventReliability, (byte)eventReliability }, { (byte)ParameterCode.EventReceiver, (byte)eventReceiver } }; if (eventData != null) { data.Add((byte)ParameterCode.EventData, eventData); } if (itemId != null) { data.Add((byte)ParameterCode.ItemId, itemId); } if (itemType.HasValue) { data.Add((byte)ParameterCode.ItemType, itemType.Value); } client.SendOperation((byte)OperationCode.RaiseGenericEvent, data, true); }
/// <summary> /// Creates a replaying wrapper for a former transport. /// </summary> /// <param name="recorder">Millepede recorder</param> /// <param name="milliTransportDescriptor">the millipede descriptor for this object</param> /// <param name="transportName">the <see cref="ITransport.Name"/></param> /// <param name="capabilities">the <see cref="ITransport.Capabilities"/></param> /// <param name="reliabilty">the <see cref="ITransport.Reliability"/></param> /// <param name="ordering">the <see cref="ITransport.Ordering"/></param> /// <param name="maxPacketSize">the <see cref="ITransport.MaximumPacketSize"/></param> public MillipedeTransport(MillipedeRecorder recorder, object milliTransportDescriptor, string transportName, IDictionary<string, string> capabilities, Reliability reliabilty, Ordering ordering, uint maxPacketSize) { Debug.Assert(recorder.Mode == MillipedeMode.Playback); this.recorder = recorder; milliDescriptor = milliTransportDescriptor; replayName = transportName; replayCapabilities = capabilities; replayReliability = reliabilty; replayOrdering = ordering; replayMaximumPacketSize = maxPacketSize; running = true; }
public void SendPackage(Player player, Package message, int mtuSize, ref int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { if (message == null) return; PlayerNetworkSession session; if (_playerSessions.TryGetValue(player.EndPoint, out session)) { Datagram.CreateDatagrams(message, mtuSize, ref reliableMessageNumber, session, SendDatagram); message.PutPool(); } Thread.Sleep(1); // Really important to slow down speed a bit }
public void SendPackage(Player player, List<Package> messages, int mtuSize, ref int reliableMessageNumber, Reliability reliability = Reliability.Reliable) { if (messages.Count == 0) return; Datagram.CreateDatagrams(messages, mtuSize, ref reliableMessageNumber, player.EndPoint, SendDatagram); PlayerNetworkSession session; if (_playerSessions.TryGetValue(player.EndPoint, out session)) { foreach (var message in messages) { //if (!player.IsBot) Thread.Sleep(7); // 7 is a good value if (!player.IsBot) { if (session.ErrorCount > 50) { if (!session.IsSlowClient) { session.IsSlowClient = true; //player.Level.BroadcastTextMessage("Slow client detected, slowing down speed for " + player.Username, type: MessageType.Raw); } // This is to slow down chunk-sending not to overrun old devices. // The timeout should be configurable and enable/disable. if (Math.Floor(player.Rtt/10d) > 0) { Thread.Sleep(Math.Min(Math.Max((int) Math.Floor(player.Rtt/10d), 7), 20)); } } else { Thread.Sleep(3); // Seems to be needed regardless :-( } } if (message is InternalPing) { ServerInfo.Latency = (ServerInfo.Latency*9 + message.Timer.ElapsedMilliseconds)/10; } TraceSend(message); message.PutPool(); } } }
/// <summary> /// The raise generic event. /// </summary> /// <param name="itemId"> /// The item id. /// </param> /// <param name="itemType"> /// The item type. /// </param> /// <param name="customEventCode"> /// The custom event code. /// </param> /// <param name="eventData"> /// The event data. /// </param> /// <param name="eventReliability"> /// The event reliability. /// </param> /// <param name="eventReceiver"> /// The event receiver. /// </param> /// <returns> /// the OperationRequest /// </returns> public static OperationRequest RaiseGenericEvent( string itemId, byte? itemType, byte customEventCode, object eventData, Reliability eventReliability, EventReceiver eventReceiver) { var request = new OperationRequest { OperationCode = (byte)OperationCode.RaiseGenericEvent, Parameters = new Dictionary<byte, object>() }; request.Parameters.Add((byte)ParameterCode.CustomEventCode, customEventCode); if (eventData != null) { request.Parameters.Add((byte)ParameterCode.EventData, eventData); } request.Parameters.Add((byte)ParameterCode.EventReliability, (byte)eventReliability); request.Parameters.Add((byte)ParameterCode.EventReceiver, (byte)eventReceiver); if (itemId != null) { request.Parameters.Add((byte)ParameterCode.ItemId, itemId); } if (itemType.HasValue) { request.Parameters.Add((byte)ParameterCode.ItemType, itemType.Value); } return request; }
/// <summary> /// The try parse event data. /// </summary> /// <param name = "data"> /// The data. /// </param> /// <param name = "reliability"> /// The reliability. /// </param> /// <param name = "channelId"> /// The channel id. /// </param> /// <param name = "eventData"> /// The event data. /// </param> /// <returns> /// Always false. /// </returns> public bool TryParseEventData(byte[] data, Reliability reliability, byte channelId, out EventData eventData) { eventData = null; return false; }
public static PropertyStates NewReliability(Reliability reliability) { return new ReliabilityWrapper(reliability); }
public NullTransport(Reliability reliability, Ordering ordering, int delay, uint maxPacketSize) { Active = true; Reliability = reliability; Ordering = ordering; Delay = delay; MaximumPacketSize = maxPacketSize; }
/// <summary> /// Constructor to set the 3 most common value /// </summary> /// <param name="d">the required reliability</param> /// <param name="a">the desired aggregation</param> /// <param name="o">the required ordered</param> public ChannelDeliveryRequirements(Reliability d, MessageAggregation a, Ordering o) { Reliability = d; Aggregation = a; Ordering = o; Freshness = Freshness.IncludeAll; }