public void Decode(NetIncomingMessage im) { this.BlockID = im.ReadByte(); this.X = im.ReadInt16(); this.Y = im.ReadInt16(); this.Z = im.ReadByte(); }
private static void HandleMessage(NetIncomingMessage inc, NetServer server) { switch (inc.MessageType) { case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request if (inc.ReadByte() == (byte) PacketTypes.Headers.Login) { string username = inc.ReadString(); Console.WriteLine("New Login Request from: {0}", username); if (username.Length > 1 & Players.Values.All(c => c.Name != username) & !_badwordList.Contains(username, StringComparer.OrdinalIgnoreCase)) { inc.SenderConnection.Approve(); NetOutgoingMessage connectedMessage = server.CreateMessage(); Thread.Sleep(500); Console.WriteLine("Sending a ack to {0}", username); connectedMessage.Write((byte) PacketTypes.Headers.LoggedIn); connectedMessage.Write(true); server.SendMessage(connectedMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered); } else { inc.SenderConnection.Deny("Bad Username"); } } break; case NetIncomingMessageType.Data: byte packetheader = inc.ReadByte(); HandleProtocol(inc, packetheader, server); break; case NetIncomingMessageType.StatusChanged: Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status); if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected) { Console.WriteLine("Player: {0} has disconnected", Players[inc.SenderConnection.RemoteUniqueIdentifier].Name); Players.Remove(inc.SenderConnection.RemoteUniqueIdentifier); } break; case NetIncomingMessageType.DiscoveryRequest: NetOutgoingMessage discovermsg = server.CreateMessage(); discovermsg.Write("Hey I just met you, I'm a server, so address me maybe"); Console.WriteLine(@"Auto Discovery Request"); server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint); break; case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.VerboseDebugMessage: Console.WriteLine(@"---Debug---"); Console.WriteLine(inc.ReadString()); Console.WriteLine(@"---End---"); break; } }
public override void Decode(NetIncomingMessage msg) { findSixes = msg.ReadBoolean(); nPosition = new HashSet<int>(); for (int i = msg.ReadByte(); i > 0; i--) nPosition.Add(msg.ReadByte()); }
public void readData(NetIncomingMessage msg) { while (msg.PositionInBytes < msg.LengthBytes) { Console.WriteLine("Data in buffer : " + (msg.LengthBytes - msg.PositionInBytes)); PacketTypes pa = (PacketTypes)msg.ReadByte(); Console.WriteLine(pa); switch (pa) { case PacketTypes.ClientInput: InputObject input = new InputObject(); InputParser.readBytes(msg, ref input); Player p = Players[msg.SenderConnection.RemoteUniqueIdentifier]; p.Input = input; break; default: Console.WriteLine("overflow : " + msg.ReadByte()); break; } } }
public void Decode(NetIncomingMessage im) { this.Username = im.ReadString(); this.ID = im.ReadByte(); this.Me = im.ReadBoolean(); this.Color = new Color(im.ReadByte(), im.ReadByte(), im.ReadByte()); }
public static void readBytes(NetIncomingMessage data, ref InputObject io) { data.ReadByte(); Console.WriteLine(io.HorizontalAxis = data.ReadFloat()); Console.WriteLine(io.VerticalAxis = data.ReadFloat()); Console.WriteLine(io.AmingAngle = data.ReadFloat()); Console.WriteLine(io.Buttons = data.ReadByte()); }
public static PlayerInformation Read(NetIncomingMessage packet) { Byte slot = packet.ReadByte(); TeamType team = (TeamType)packet.ReadByte(); String callsign = packet.ReadString(); String tag = packet.ReadString(); return new PlayerInformation(slot, callsign, tag, team); }
/// <summary> /// Handles an incoming entity component message /// </summary> /// <param name="message">Raw network message</param> /// <returns>An IncomingEntityComponentMessage object</returns> public IncomingEntityComponentMessage HandleEntityComponentNetworkMessage(NetIncomingMessage message) { var componentFamily = (ComponentFamily) message.ReadByte(); var messageParams = new List<object>(); while (message.Position < message.LengthBits) { switch ((NetworkDataType) message.ReadByte()) { case NetworkDataType.d_enum: messageParams.Add(message.ReadInt32()); break; case NetworkDataType.d_bool: messageParams.Add(message.ReadBoolean()); break; case NetworkDataType.d_byte: messageParams.Add(message.ReadByte()); break; case NetworkDataType.d_sbyte: messageParams.Add(message.ReadSByte()); break; case NetworkDataType.d_ushort: messageParams.Add(message.ReadUInt16()); break; case NetworkDataType.d_short: messageParams.Add(message.ReadInt16()); break; case NetworkDataType.d_int: messageParams.Add(message.ReadInt32()); break; case NetworkDataType.d_uint: messageParams.Add(message.ReadUInt32()); break; case NetworkDataType.d_ulong: messageParams.Add(message.ReadUInt64()); break; case NetworkDataType.d_long: messageParams.Add(message.ReadInt64()); break; case NetworkDataType.d_float: messageParams.Add(message.ReadFloat()); break; case NetworkDataType.d_double: messageParams.Add(message.ReadDouble()); break; case NetworkDataType.d_string: messageParams.Add(message.ReadString()); break; case NetworkDataType.d_byteArray: int length = message.ReadInt32(); messageParams.Add(message.ReadBytes(length)); break; } } return new IncomingEntityComponentMessage(componentFamily, messageParams); }
public void Decode(NetIncomingMessage im) { this.ServerName = im.ReadString(); this.Description = im.ReadString(); this.Intro = im.ReadString(); this.Online = im.ReadByte(); int roomsLength = im.ReadByte(); for (int i = 0; i < roomsLength; i++) { Rooms.Add(new LobbySaveData(im.ReadString(), im.ReadInt16(), im.ReadString(), im.ReadByte(), im.ReadInt16(), im.ReadDouble())); } }
public override void OnAdvancedNetworkMessage(NetIncomingMessage msg) { if (msg.ReadByte() == 0) { this.lxLoot = new List<PreSeededLoot>(); byte byCount = msg.ReadByte(); for (int i = 0; i < (int)byCount; i++) { this.lxLoot.Add(new PreSeededLoot(msg.ReadUInt16(), (ItemCodex.ItemTypes)msg.ReadInt32(), new Vector2(msg.ReadFloat(), msg.ReadFloat()))); } } }
/// <summary> /// /// </summary> /// <param name="incomingMsg"></param> public void HandleData(NetIncomingMessage incomingMsg) { MessageType messageType = (MessageType)incomingMsg.ReadByte(); switch (messageType) { case MessageType.MsgState: SendState(); break; case MessageType.MsgPlayerClientUpdate: BroadcastUpdate(incomingMsg); break; case MessageType.MsgDeath: Die(incomingMsg); break; case MessageType.MsgBeginShot: Shoot(incomingMsg); break; case MessageType.MsgEndShot: EndShot(incomingMsg); break; default: break; } }
protected override void Read(NetIncomingMessage message) { x = message.ReadFloat(); y = message.ReadFloat(); rotation = message.ReadUInt16().FromNetworkRotation() * (180f / (float)Math.PI); type = message.ReadByte(); }
static object ReadArgument(NetIncomingMessage msg, Type type) { if (type == typeof(int)) { return msg.ReadInt32(); } else if (type == typeof(byte)) { return msg.ReadByte(); } else if (type == typeof(float)) { return msg.ReadFloat(); } else if (type == typeof(Vector3)) { return NetworkUtils.ReadVector3(msg); } else if (type == typeof(Quaternion)) { return NetworkUtils.ReadQuaternion(msg); } else if (type == typeof(string)) { return msg.ReadString(); } else { throw new Exception("Unsupported argument type " + type); } }
public LidgrenStatusChangeMessageContext(NetIncomingMessage incomingMessage) : base(incomingMessage) { LidgrenStatus = (NetConnectionStatus)incomingMessage.ReadByte(); //Generate a Lidgren status message for dispatching GeneratedStatusMessage = new LidgrenStatusMessage(LidgrenStatus); }
private void Data(NetIncomingMessage inc) { var packetType = (PacketType) inc.ReadByte(); var gameRoom = GetGameRoomById(inc.ReadString()); var command = PacketFactory.GetCommand(packetType); command.Run(_managerLogger, this,inc, null, gameRoom); }
public static NetObject ReadFromMessage(NetIncomingMessage message) { var type = (NetObjectType)message.ReadByte(); var instance = (NetObject)Activator.CreateInstance(netObjectTypes[type]); instance.Read(message); return instance; }
public static new Packet FromNetBuffer(NetIncomingMessage incomingMessage) { var id = incomingMessage.ReadInt32(); var type = (ContentType)incomingMessage.ReadByte(); var packet = new ContentReleasePacket(type, id); return packet; }
public void R(NetIncomingMessage im) { Operat = im.ReadByte(); UserId = im.ReadUInt32(); if (Operat == Add || Operat == Changed) { Tag = im.ReadUInt32(); if (GameMessageHelper.Is_Changed(Tag, GameMessageHelper.POSITION_TAG)) { X = im.ReadFloat(); Y = im.ReadFloat(); } if (GameMessageHelper.Is_Changed(Tag, GameMessageHelper.RADIUS_TAG)) { Radius = im.ReadInt32(); } if (GameMessageHelper.Is_Changed(Tag, GameMessageHelper.COLOR_TAG)) { Color = im.ReadUInt32(); } if (GameMessageHelper.Is_Changed(Tag, GameMessageHelper.NAME_TAG)) { Name = im.ReadString(); } } }
private static Packet ReadFromMessage(NetIncomingMessage message) { var id = (PacketId)message.ReadByte(); var instance = (Packet)Activator.CreateInstance(packetTypes[id]); instance.Read(message); return instance; }
public static Packet decode(ref NetIncomingMessage msg) { Packet p = new Packet (0); p.type = msg.ReadByte (); p.clientId = msg.ReadInt32 (); return p; }
/// <summary> /// Writes a <see cref="NetIncomingMessage"/> buffer into the BitStream. /// </summary> /// <param name="source">The <see cref="NetIncomingMessage"/> who's contents will be copied to this BitStream.</param> public void Write(NetIncomingMessage source) { #if DEBUG var startBSPos = PositionBits; var startMsgPos = (int)source.Position; #endif // Read full 32-bit integers while (source.LengthBits - source.Position >= _bitsInt) { var v = source.ReadUInt32(); Write(v); } // Read full 8-bit integers while (source.LengthBits - source.Position >= _bitsByte) { var v = source.ReadByte(); Write(v); } // Read the remaining bits while (source.LengthBits > source.Position) { var v = source.ReadBoolean(); Write(v); } Debug.Assert(source.Position == source.LengthBits); #if DEBUG Debug.Assert(PositionBits - startBSPos == source.LengthBits - startMsgPos); #endif }
public void ReceiveMessage(object sender, NetIncomingMessage msg) { #if !EXTERNAL UnityEngine.Debug.Log("Got message [" + msg.LengthBytes + "B]"); #else Console.WriteLine("Got message [" + msg.LengthBytes + "B]"); #endif MsgType type = (MsgType)msg.ReadByte(); switch (type) { case MsgType.RecommendationRequest: if (this.RecommendationRequested != null) this.RecommendationRequested(msg); break; case MsgType.RecommendationContent: if (this.RecommendationReceived != null) this.RecommendationReceived(msg); break; case MsgType.RecommendationSelected: if (this.RecommendationSelected != null) this.RecommendationSelected(msg); break; case MsgType.ObjectsFreed: if (this.ObjectsFreed != null) this.ObjectsFreed(msg); break; case MsgType.Sentiments: if (this.Sentiments != null) this.Sentiments(msg); break; default: break; } }
public void Decode(NetIncomingMessage im) { this.ID = im.ReadByte(); this.Message = im.ReadString(); if (Message.Length > Networking.Messages.ChatMessage.MaxLength) Message= Message.Truncate(Networking.Messages.ChatMessage.MaxLength); }
public void Run(ManagerLogger managerLogger, Server server, NetIncomingMessage inc, PlayerAndConnection playerAndConnection, GameRoom gameRoom) { managerLogger.AddLogMessage("server", "New connection..."); var data = inc.ReadByte(); if (data == (byte)PacketType.Login) { managerLogger.AddLogMessage("server", "..connection accpeted."); playerAndConnection = CreatePlayer(inc, gameRoom.Players, gameRoom.ManagerCamera); inc.SenderConnection.Approve(); var outmsg = server.NetServer.CreateMessage(); outmsg.Write((byte)PacketType.Login); outmsg.Write(true); outmsg.Write(gameRoom.Players.Count); for (int n = 0; n < gameRoom.Players.Count; n++) { var p = gameRoom.Players[n]; outmsg.Write(p.Player.Username); outmsg.WriteAllProperties(p.Player.Position); } server.NetServer.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0); var command = new PlayerPositionCommand(); command.Run(managerLogger, server,inc,playerAndConnection,gameRoom); server.SendNewPlayerEvent(playerAndConnection.Player.Username, gameRoom.GameRoomId); } else { inc.SenderConnection.Deny("Didn't send correct information."); } }
public void Decode(NetIncomingMessage im) { this.ID = im.ReadByte(); this.Position = new Point(im.ReadInt32(), im.ReadInt32()); this.Velocity = new Point(im.ReadInt32(), im.ReadInt32()); this.Movement = new Point(im.ReadInt32(), im.ReadInt32()); this.IsJumping = im.ReadBoolean(); }
public static Packet ReadFromMessage(NetIncomingMessage msg) { PacketType type = (PacketType)msg.ReadByte(); Packet packet = (Packet)Activator.CreateInstance(PacketTypes[type]); packet.Read(msg); return packet; }
public void StatusCallbackImpl(NetServer server, NetIncomingMessage msg) { NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte(); if (status == NetConnectionStatus.Disconnected) { RemoveFarmObj(msg.SenderConnection); } }
public void HandleData(NetIncomingMessage msg) { NetMsgType datatype = (NetMsgType)msg.ReadByte(); if (datatype == NetMsgType.Control) { Soul soul = (Soul)msg.SenderConnection.Tag; var key = (ControlKey)msg.ReadByte(); var edge = msg.ReadBoolean(); //Console.WriteLine("Received Control Message: " + key + (edge ? "Pressed" : "Released")); soul.currentShip.Controls.ReceiveMessage(key, edge); } else if (datatype == NetMsgType.ControlUpdate) { Soul soul = (Soul)msg.SenderConnection.Tag; var Pitch = msg.ReadFloat(); var Yaw = msg.ReadFloat(); var Roll = msg.ReadFloat(); soul.currentShip.Controls.ReceiveMessage(Pitch, Yaw, Roll); } else if (datatype == NetMsgType.ShipDataOutput) { ShipDataOutputMessage data; data = new ShipDataOutputMessage(msg); Soul soul = new Soul(msg.SenderConnection); soul.currentSector = Sector.Redria; msg.SenderConnection.Tag = soul; soul.currentSector.Terrain.Load(msg.SenderConnection); soul.currentSector.Ships.Load(msg.SenderConnection); soul.currentSector.Objects.Load(msg.SenderConnection); var idRandomizer = new Random(); var NewShip = new ShipObj(new Vector3(0, 100, 2), Quaternion.Identity, data.GeneratedData); soul.currentShip = NewShip; NewShip.Client = soul; //Console.WriteLine(msg.SenderEndpoint.Address + "'s Ship ID: " + NewShip.ID); foreach (NetConnection c in Network.Server.Connections) { MessageWriter.ClientEntityCreationMessage(c, NewShip.ID, NewShip.Position, NewShip.Orientation, data.GeneratedData.NoseID, data.GeneratedData.CoreID, data.GeneratedData.EngineID, data.Weapons, msg.SenderConnection.RemoteUniqueIdentifier); } } }
protected override void Read(NetIncomingMessage message) { Name = message.ReadString(); X = message.ReadFloat(); Y = message.ReadFloat(); rotation = message.ReadUInt16().FromNetworkRotation() * (180f / (float)Math.PI); Health = message.ReadByte() / (float)byte.MaxValue; }
public static void readBytes(NetIncomingMessage data, ClientSprite cs) { data.ReadByte(); cs.ID = data.ReadUInt32(); cs.SpriteID = (SpriteIDs)data.ReadUInt16(); cs.Position = new Microsoft.Xna.Framework.Vector2(data.ReadFloat(),data.ReadFloat()); cs.Rotation = data.ReadFloat(); }
/// <summary> /// Called when host/client receives a NatIntroduction message from a master server /// </summary> private void HandleNatIntroduction(int ptr) { VerifyNetworkThread(); // read intro NetIncomingMessage tmp = SetupReadHelperMessage(ptr, 1000); // never mind length byte hostByte = tmp.ReadByte(); IPEndPoint remoteInternal = tmp.ReadIPEndpoint(); IPEndPoint remoteExternal = tmp.ReadIPEndpoint(); string token = tmp.ReadString(); bool isHost = (hostByte != 0); LogDebug("NAT introduction received; we are designated " + (isHost ? "host" : "client")); NetOutgoingMessage punch; if (!isHost && m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess) == false) { return; // no need to punch - we're not listening for nat intros! } #if DEBUG LogDebug("Enqueuing internal Punch message" + remoteInternal.ToString()); #endif // send internal punch punch = CreateMessage(1); punch.m_messageType = NetMessageType.NatPunchMessage; punch.Write(hostByte); punch.Write(token); m_unsentUnconnectedMessages.Enqueue(new NetTuple <IPEndPoint, NetOutgoingMessage>(remoteInternal, punch)); #if DEBUG LogDebug("Enqueuing External Punch message to " + remoteExternal.ToString()); #endif // send external punch punch = CreateMessage(1); punch.m_messageType = NetMessageType.NatPunchMessage; punch.Write(hostByte); punch.Write(token); m_unsentUnconnectedMessages.Enqueue(new NetTuple <IPEndPoint, NetOutgoingMessage>(remoteExternal, punch)); }
/// <summary> /// Called when host/client receives a NatIntroduction message from a master server /// </summary> internal void HandleNatIntroduction(int offset) { AssertIsOnLibraryThread(); // read intro NetIncomingMessage tmp = SetupReadHelperMessage(offset, 1000); // never mind length byte hostByte = tmp.ReadByte(); IPEndPoint remoteInternal = tmp.ReadIPEndPoint(); IPEndPoint remoteExternal = tmp.ReadIPEndPoint(); string token = tmp.ReadString(); bool isHost = hostByte != 0; LogDebug(NetLogMessage.FromValues(NetLogCode.NATIntroductionReceived, value: hostByte)); if (!isHost && !Configuration.IsMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess)) { return; // no need to punch - we're not listening for nat intros! } // send internal punch var internalPunch = CreateMessage(1); internalPunch._messageType = NetMessageType.NatPunchMessage; internalPunch.Write(hostByte); internalPunch.Write(token); UnsentUnconnectedMessages.Enqueue((remoteInternal, internalPunch)); LogDebug(new NetLogMessage(NetLogCode.NATPunchSent, endPoint: remoteInternal)); // send external punch var externalPunch = CreateMessage(1); externalPunch._messageType = NetMessageType.NatPunchMessage; externalPunch.Write(hostByte); externalPunch.Write(token); UnsentUnconnectedMessages.Enqueue((remoteExternal, externalPunch)); LogDebug(new NetLogMessage(NetLogCode.NATPunchSent, endPoint: remoteExternal)); }
/// <summary> /// Called when host/client receives a NatIntroduction message from a master server /// </summary> internal void HandleNatIntroduction(int ptr) { // read intro NetIncomingMessage tmp = SetupReadHelperMessage(ptr, 1000); // never mind length byte hostByte = tmp.ReadByte(); NetEndPoint remoteInternal = tmp.ReadIPEndPoint(); NetEndPoint remoteExternal = tmp.ReadIPEndPoint(); string token = tmp.ReadString(); bool isHost = (hostByte != 0); LogDebug("NAT introduction received; we are designated " + (isHost ? "host" : "client")); NetOutgoingMessage punch; if (!isHost && m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess) == false) { return; // no need to punch - we're not listening for nat intros! } // send internal punch punch = CreateMessage(1); punch.m_messageType = NetMessageType.NatPunchMessage; punch.Write(hostByte); punch.Write(token); Interlocked.Increment(ref punch.m_recyclingCount); m_unsentUnconnectedMessages.Enqueue(new NetTuple <NetEndPoint, NetOutgoingMessage>(remoteInternal, punch)); LogDebug("NAT punch sent to " + remoteInternal); // send external punch punch = CreateMessage(1); punch.m_messageType = NetMessageType.NatPunchMessage; punch.Write(hostByte); punch.Write(token); Interlocked.Increment(ref punch.m_recyclingCount); m_unsentUnconnectedMessages.Enqueue(new NetTuple <NetEndPoint, NetOutgoingMessage>(remoteExternal, punch)); LogDebug("NAT punch sent to " + remoteExternal); }
private void HandleNatPunchConfirmed(int ptr, NetEndPoint senderEndPoint) { NetIncomingMessage tmp = SetupReadHelperMessage(ptr, 1000); // never mind length var isFromClient = tmp.ReadByte() == ClientByte; if (isFromClient) { LogDebug("NAT punch confirmation received from " + senderEndPoint + " we're host, so we ignore this"); return; } string token = tmp.ReadString(); LogDebug("NAT punch confirmation received from " + senderEndPoint + " we're client so we go ahead and succeed the introduction"); // // Release punch success to client; enabling him to Connect() to msg.Sender if token is ok // NetIncomingMessage punchSuccess = CreateIncomingMessage(NetIncomingMessageType.NatIntroductionSuccess, 10); punchSuccess.m_senderEndPoint = senderEndPoint; punchSuccess.Write(token); ReleaseMessage(punchSuccess); }
// received a library message while Connected internal void ReceivedLibraryMessage(NetMessageType tp, int ptr, int payloadLength) { m_peer.VerifyNetworkThread(); float now = (float)NetTime.Now; switch (tp) { case NetMessageType.Connect: m_peer.LogDebug("Received handshake message (" + tp + ") despite connection being in place"); break; case NetMessageType.ConnectResponse: // handshake message must have been lost HandleConnectResponse(now, tp, ptr, payloadLength); break; case NetMessageType.ConnectionEstablished: // do nothing, all's well break; case NetMessageType.LibraryError: m_peer.ThrowOrLog("LibraryError received by ReceivedLibraryMessage; this usually indicates a malformed message"); break; case NetMessageType.Disconnect: NetIncomingMessage msg = m_peer.SetupReadHelperMessage(ptr, payloadLength); m_disconnectRequested = true; m_disconnectMessage = msg.ReadString(); m_disconnectReqSendBye = false; //ExecuteDisconnect(msg.ReadString(), false); break; case NetMessageType.Acknowledge: for (int i = 0; i < payloadLength; i += 3) { NetMessageType acktp = (NetMessageType)m_peer.m_receiveBuffer[ptr++]; // netmessagetype int seqNr = m_peer.m_receiveBuffer[ptr++]; seqNr |= (m_peer.m_receiveBuffer[ptr++] << 8); // need to enqueue this and handle it in the netconnection heartbeat; so be able to send resends together with normal sends m_queuedIncomingAcks.Enqueue(new NetTuple <NetMessageType, int>(acktp, seqNr)); } break; case NetMessageType.Ping: int pingNr = m_peer.m_receiveBuffer[ptr++]; SendPong(pingNr); break; case NetMessageType.Pong: NetIncomingMessage pmsg = m_peer.SetupReadHelperMessage(ptr, payloadLength); int pongNr = pmsg.ReadByte(); float remoteSendTime = pmsg.ReadSingle(); ReceivedPong(now, pongNr, remoteSendTime); break; case NetMessageType.ExpandMTURequest: SendMTUSuccess(payloadLength); break; case NetMessageType.ExpandMTUSuccess: if (m_peer.Configuration.AutoExpandMTU == false) { m_peer.LogDebug("Received ExpandMTURequest altho AutoExpandMTU is turned off!"); break; } NetIncomingMessage emsg = m_peer.SetupReadHelperMessage(ptr, payloadLength); int size = emsg.ReadInt32(); HandleExpandMTUSuccess(now, size); break; case NetMessageType.NatIntroduction: // Unusual situation where server is actually already known, but got a nat introduction - oh well, lets handle it as usual m_peer.HandleNatIntroduction(ptr); break; default: m_peer.LogWarning("Connection received unhandled library message: " + tp); break; } }
internal void ReceivedHandshake(double now, NetMessageType tp, int ptr, int payloadLength) { m_peer.VerifyNetworkThread(); byte[] hail; switch (tp) { case NetMessageType.Connect: if (m_status == NetConnectionStatus.ReceivedInitiation) { // Whee! Server full has already been checked bool ok = ValidateHandshakeData(ptr, payloadLength, out hail); if (ok) { if (hail != null) { m_remoteHailMessage = m_peer.CreateIncomingMessage(NetIncomingMessageType.Data, hail); m_remoteHailMessage.LengthBits = (hail.Length * 8); } else { m_remoteHailMessage = null; } if (m_peerConfiguration.IsMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval)) { // ok, let's not add connection just yet NetIncomingMessage appMsg = m_peer.CreateIncomingMessage(NetIncomingMessageType.ConnectionApproval, (m_remoteHailMessage == null ? 0 : m_remoteHailMessage.LengthBytes)); appMsg.m_receiveTime = now; appMsg.m_senderConnection = this; appMsg.m_senderEndPoint = this.m_remoteEndPoint; if (m_remoteHailMessage != null) { appMsg.Write(m_remoteHailMessage.m_data, 0, m_remoteHailMessage.LengthBytes); } SetStatus(NetConnectionStatus.RespondedAwaitingApproval, NetConnectionResult.AwaitingApproval); m_peer.ReleaseMessage(appMsg); return; } SendConnectResponse((float)now, true); } return; } if (m_status == NetConnectionStatus.RespondedAwaitingApproval) { m_peer.LogWarning("Ignoring multiple Connect() most likely due to a delayed Approval"); return; } if (m_status == NetConnectionStatus.RespondedConnect) { // our ConnectResponse must have been lost SendConnectResponse((float)now, true); return; } m_peer.LogDebug("Unhandled Connect: " + tp + ", status is " + m_status + " length: " + payloadLength); break; case NetMessageType.ConnectResponse: HandleConnectResponse(now, tp, ptr, payloadLength); break; case NetMessageType.ConnectionEstablished: switch (m_status) { case NetConnectionStatus.Connected: // ok... break; case NetConnectionStatus.Disconnected: case NetConnectionStatus.Disconnecting: case NetConnectionStatus.None: // too bad, almost made it break; case NetConnectionStatus.ReceivedInitiation: // uh, a little premature... ignore break; case NetConnectionStatus.InitiatedConnect: // weird, should have been RespondedConnect... break; case NetConnectionStatus.RespondedConnect: // awesome NetIncomingMessage msg = m_peer.SetupReadHelperMessage(ptr, payloadLength); InitializeRemoteTimeOffset(msg.ReadSingle()); m_peer.AcceptConnection(this); InitializePing(); SetStatus(NetConnectionStatus.Connected, NetConnectionResult.Connected); return; } break; case NetMessageType.Disconnect: // ouch var reason = NetConnectionResult.Unknown; try { NetIncomingMessage inc = m_peer.SetupReadHelperMessage(ptr, payloadLength); reason = (NetConnectionResult)inc.ReadByte(); } catch { } ExecuteDisconnect(reason, false); break; case NetMessageType.Discovery: m_peer.HandleIncomingDiscoveryRequest(now, m_remoteEndPoint, ptr, payloadLength); return; case NetMessageType.DiscoveryResponse: m_peer.HandleIncomingDiscoveryResponse(now, m_remoteEndPoint, ptr, payloadLength); return; case NetMessageType.Ping: // silently ignore return; default: m_peer.LogDebug("Unhandled type during handshake: " + tp + " length: " + payloadLength); break; } }
// received a library message while Connected internal void ReceivedLibraryMessage(NetMessageType tp, int ptr, int payloadLength) { m_peer.VerifyNetworkThread(); float now = (float)NetTime.Now; switch (tp) { case NetMessageType.Disconnect: NetIncomingMessage msg = m_peer.SetupReadHelperMessage(ptr, payloadLength); ExecuteDisconnect(msg.ReadString(), false); break; case NetMessageType.Acknowledge: for (int i = 0; i < payloadLength; i += 3) { NetMessageType acktp = (NetMessageType)m_peer.m_receiveBuffer[ptr++]; // netmessagetype int seqNr = m_peer.m_receiveBuffer[ptr++]; seqNr |= (m_peer.m_receiveBuffer[ptr++] << 8); // need to enqueue this and handle it in the netconnection heartbeat; so be able to send resends together with normal sends m_queuedIncomingAcks.Enqueue(new NetTuple <NetMessageType, int>(acktp, seqNr)); } break; case NetMessageType.Ping: int pingNr = m_peer.m_receiveBuffer[ptr++]; SendPong(pingNr); break; case NetMessageType.Pong: NetIncomingMessage pmsg = m_peer.SetupReadHelperMessage(ptr, payloadLength); int pongNr = pmsg.ReadByte(); float remoteSendTime = pmsg.ReadSingle(); ReceivedPong(now, pongNr, remoteSendTime); break; case NetMessageType.ExpandMTURequest: SendMTUSuccess(payloadLength); break; case NetMessageType.ExpandMTUSuccess: NetIncomingMessage emsg = m_peer.SetupReadHelperMessage(ptr, payloadLength); int size = emsg.ReadInt32(); HandleExpandMTUSuccess(now, size); break; case NetMessageType.NatIntroduction: // Unusual situation where server is actually already known, but got a nat introduction - oh well, lets handle it as usual m_peer.HandleNatIntroduction(ptr); break; case NetMessageType.ConnectResponse: // Lidgren bug fix -AR // ConnectionEstablished (from handshake) must have been lost, send another one m_peer.LogDebug("Resending ConnectionEstablished..."); SendConnectionEstablished(); break; default: m_peer.LogWarning("Connection received unhandled library message: " + tp); break; } }
private void Heartbeat() { VerifyNetworkThread(); double dnow = NetTime.Now; float now = (float)dnow; double delta = dnow - m_lastHeartbeat; int maxCHBpS = 1250 - m_connections.Count; if (maxCHBpS < 250) { maxCHBpS = 250; } if (delta > (1.0 / (double)maxCHBpS) || delta < 0.0) // max connection heartbeats/second max { m_frameCounter++; m_lastHeartbeat = dnow; // do handshake heartbeats if ((m_frameCounter % 3) == 0) { foreach (var kvp in m_handshakes) { NetConnection conn = kvp.Value as NetConnection; #if DEBUG // sanity check if (kvp.Key != kvp.Key) { LogWarning("Sanity fail! Connection in handshake list under wrong key!"); } #endif conn.UnconnectedHeartbeat(now); if (conn.m_status == NetConnectionStatus.Connected || conn.m_status == NetConnectionStatus.Disconnected) { #if DEBUG // sanity check if (conn.m_status == NetConnectionStatus.Disconnected && m_handshakes.ContainsKey(conn.RemoteEndPoint)) { LogWarning("Sanity fail! Handshakes list contained disconnected connection!"); m_handshakes.Remove(conn.RemoteEndPoint); } #endif break; // collection has been modified } } } #if DEBUG SendDelayedPackets(); #endif // update m_executeFlushSendQueue if (m_configuration.m_autoFlushSendQueue) { m_executeFlushSendQueue = true; } // do connection heartbeats lock (m_connections) { foreach (NetConnection conn in m_connections) { conn.Heartbeat(now, m_frameCounter); if (conn.m_status == NetConnectionStatus.Disconnected) { // // remove connection // m_connections.Remove(conn); m_connectionLookup.Remove(conn.RemoteEndPoint); break; // can't continue iteration here } } } m_executeFlushSendQueue = false; // send unsent unconnected messages NetTuple <IPEndPoint, NetOutgoingMessage> unsent; while (m_unsentUnconnectedMessages.TryDequeue(out unsent)) { NetOutgoingMessage om = unsent.Item2; bool connReset; int len = om.Encode(m_sendBuffer, 0, 0); SendPacket(len, unsent.Item1, 1, out connReset); Interlocked.Decrement(ref om.m_recyclingCount); if (om.m_recyclingCount <= 0) { Recycle(om); } } } // // read from socket // if (m_socket == null) { return; } if (!m_socket.Poll(1000, SelectMode.SelectRead)) // wait up to 1 ms for data to arrive { return; } //if (m_socket == null || m_socket.Available < 1) // return; // update now dnow = NetTime.Now; now = (float)dnow; do { int bytesReceived = 0; try { bytesReceived = m_socket.ReceiveFrom(m_receiveBuffer, 0, m_receiveBuffer.Length, SocketFlags.None, ref m_senderRemote); } catch (SocketException sx) { switch (sx.SocketErrorCode) { case SocketError.ConnectionReset: // connection reset by peer, aka connection forcibly closed aka "ICMP port unreachable" // we should shut down the connection; but m_senderRemote seemingly cannot be trusted, so which connection should we shut down?! // So, what to do? LogWarning("ConnectionReset"); return; case SocketError.NotConnected: // socket is unbound; try to rebind it (happens on mobile when process goes to sleep) BindSocket(true); return; default: LogWarning("Socket exception: " + sx.ToString()); return; } } if (bytesReceived < NetConstants.HeaderByteSize) { return; } //LogVerbose("Received " + bytesReceived + " bytes"); IPEndPoint ipsender = (IPEndPoint)m_senderRemote; if (m_upnp != null && now < m_upnp.m_discoveryResponseDeadline && bytesReceived > 32) { // is this an UPnP response? string resp = System.Text.Encoding.ASCII.GetString(m_receiveBuffer, 0, bytesReceived); if (resp.Contains("upnp:rootdevice") || resp.Contains("UPnP/1.0")) { try { resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9); resp = resp.Substring(0, resp.IndexOf("\r")).Trim(); m_upnp.ExtractServiceUrl(resp); return; } catch (Exception ex) { LogDebug("Failed to parse UPnP response: " + ex.ToString()); // don't try to parse this packet further return; } } } NetConnection sender = null; m_connectionLookup.TryGetValue(ipsender, out sender); // // parse packet into messages // int numMessages = 0; int numFragments = 0; int ptr = 0; while ((bytesReceived - ptr) >= NetConstants.HeaderByteSize) { // decode header // 8 bits - NetMessageType // 1 bit - Fragment? // 15 bits - Sequence number // 16 bits - Payload length in bits numMessages++; NetMessageType tp = (NetMessageType)m_receiveBuffer[ptr++]; byte low = m_receiveBuffer[ptr++]; byte high = m_receiveBuffer[ptr++]; bool isFragment = ((low & 1) == 1); ushort sequenceNumber = (ushort)((low >> 1) | (((int)high) << 7)); numFragments++; ushort payloadBitLength = (ushort)(m_receiveBuffer[ptr++] | (m_receiveBuffer[ptr++] << 8)); int payloadByteLength = NetUtility.BytesToHoldBits(payloadBitLength); if (bytesReceived - ptr < payloadByteLength) { LogWarning("Malformed packet; stated payload length " + payloadByteLength + ", remaining bytes " + (bytesReceived - ptr)); return; } if (tp >= NetMessageType.Unused1 && tp <= NetMessageType.Unused29) { ThrowOrLog("Unexpected NetMessageType: " + tp); return; } try { if (tp >= NetMessageType.LibraryError) { if (sender != null) { sender.ReceivedLibraryMessage(tp, ptr, payloadByteLength); } else { ReceivedUnconnectedLibraryMessage(dnow, ipsender, tp, ptr, payloadByteLength); } } else { if (sender == null && !m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData)) { return; // dropping unconnected message since it's not enabled } NetIncomingMessage msg = m_receiveBuffer[ptr] == 255 ? CreateIncomingMessage(NetIncomingMessageType.ExternalHighlevelMessage, payloadByteLength) : CreateIncomingMessage(NetIncomingMessageType.Data, payloadByteLength); msg.m_isFragment = isFragment; msg.m_receiveTime = dnow; msg.m_sequenceNumber = sequenceNumber; msg.m_receivedMessageType = tp; msg.m_senderConnection = sender; msg.m_senderEndPoint = ipsender; //This value will not be accurate and making it accurate is a waste of time. msg.m_bitLength = payloadBitLength; Buffer.BlockCopy(m_receiveBuffer, ptr, msg.m_data, 0, payloadByteLength); msg.ReadByte(); /*Console.WriteLine(""); * for (int i = 0; i < msg.Data.Length; i++) * { * Console.Write("B: " + msg.Data[i]); * }*/ if (sender != null) { if (tp == NetMessageType.Unconnected) { // We're connected; but we can still send unconnected messages to this peer msg.m_incomingMessageType = NetIncomingMessageType.UnconnectedData; ReleaseMessage(msg); } else { // connected application (non-library) message sender.ReceivedMessage(msg); } } else { // at this point we know the message type is enabled // unconnected application (non-library) message msg.m_incomingMessageType = NetIncomingMessageType.UnconnectedData; ReleaseMessage(msg); } } } catch (Exception ex) { LogError("Packet parsing error: " + ex.Message + " from " + ipsender); } ptr += payloadByteLength; } m_statistics.PacketReceived(bytesReceived, numMessages, numFragments); if (sender != null) { sender.m_statistics.PacketReceived(bytesReceived, numMessages, numFragments); } } while (m_socket.Available > 0); }