void checkToCheckup(GameTime gameTime) { if (iAmServer) { return; } timeSinceLastCheckup += (float)gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastCheckup >= checkupDelay) { timeSinceLastCheckup = 0f; NetOutgoingMessage msg = netPeer.CreateMessage(); msg.Write(MessageID.CHECKUP); netPeer.SendMessage(msg, connection, NetDeliveryMethod.ReliableUnordered); } }
internal NetOutgoingMessage ToOutgoing(NetPeer Sender) { NetOutgoingMessage msg = Sender.CreateMessage("__msg"); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); serializer.Serialize(writer, this); msg.Write(sb.ToString()); return msg; }
static void Main(string[] args) { NetPeerConfiguration config = new NetPeerConfiguration("unittests"); config.EnableUPnP = true; NetPeer peer = new NetPeer(config); peer.Start(); // needed for initialization Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier)); ReadWriteTests.Run(peer); NetQueueTests.Run(); MiscTests.Run(peer); BitVectorTests.Run(); EncryptionTests.Run(peer); var om = peer.CreateMessage(); peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242)); try { peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242)); } catch (NetException nex) { if (nex.Message != "This message has already been sent! Use NetPeer.SendMessage() to send to multiple recipients efficiently") throw nex; } peer.Shutdown("bye"); // read all message NetIncomingMessage inc = peer.WaitMessage(5000); while (inc != null) { switch (inc.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: Console.WriteLine("Peer message: " + inc.ReadString()); break; case NetIncomingMessageType.Error: throw new Exception("Received error message!"); } inc = peer.ReadMessage(); } Console.WriteLine("Done"); Console.ReadKey(); }
public static void Connect(string ip, int port, params object[] data) { Peer = new NetClient(DefaultConfiguration); Peer.Start(); var hailMessage = Peer.CreateMessage(); foreach (var o in data) { hailMessage.Write(o); } Peer.Connect(ip, port, hailMessage); }
/// <summary> /// Gets a <see cref="NetOutgoingMessage"/>. /// </summary> /// <param name="netPeer">The <see cref="NetPeer"/> instance that the message is to be used on.</param> /// <param name="size">The minimum initial size of the <see cref="NetOutgoingMessage"/> in bytes.</param> /// <returns> /// The <see cref="NetOutgoingMessage"/> instance to use. /// </returns> public static NetOutgoingMessage GetNetOutgoingMessage(NetPeer netPeer, int size) { // Round up to the next power-of-2 size (if not already there) to make allocations a bit more consistency-sized // and grabbing from the internal pool will hopefully be faster, even if it does mean over-allocating a bit more. // Also, never use less than 16 bytes since there is not much point in cluttering things up with tiny buffers. if (size < 16) size = 16; else size = BitOps.NextPowerOf2(size); // Grab the NetOutgoingMessage from the internal buffer return netPeer.CreateMessage(size); }
public static void Run(NetPeer peer) { // // Test XTEA // NetXtea xtea = new NetXtea("TopSecret"); byte[] original = new byte[16]; NetRandom.Instance.NextBytes(original); byte[] encrypted = new byte[original.Length]; xtea.EncryptBlock(original, 0, encrypted, 0); xtea.EncryptBlock(original, 8, encrypted, 8); byte[] decrypted = new byte[original.Length]; xtea.DecryptBlock(encrypted, 0, decrypted, 0); xtea.DecryptBlock(encrypted, 8, decrypted, 8); // compare! for (int i = 0; i < original.Length; i++) if (original[i] != decrypted[i]) throw new NetException("XTEA fail!"); Console.WriteLine("XTEA OK"); NetOutgoingMessage om = peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); om.Encrypt(xtea); // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits); im.Decrypt(xtea); if (im.ReadString() != "Hallon") throw new NetException("fail"); if (im.ReadInt32() != 42) throw new NetException("fail"); if (im.ReadInt32(5) != 5) throw new NetException("fail"); if (im.ReadBoolean() != true) throw new NetException("fail"); if (im.ReadString() != "kokos") throw new NetException("fail"); Console.WriteLine("Message encryption OK"); }
public static void RequestNATIntroduction(IPEndPoint host, NetPeer peer) { if (host == null) { return; } if (m_masterServer == null) throw new Exception("Must connect to master server first!"); NetOutgoingMessage om = peer.CreateMessage(); om.Write((byte)2); // NAT intro request // write internal ipendpoint IPAddress addr = IPAddress.Parse(GetMyLocalIpAddress()); om.Write(new IPEndPoint(addr, peer.Port)); // write external address of host to request introduction to IPEndPoint hostEp = new IPEndPoint(host.Address, port); om.Write(hostEp); om.Write(peer.Configuration.AppIdentifier); // send the app id peer.SendUnconnectedMessage(om, m_masterServer); }
public void CheckForStatusUpdate(GameTime gameTime, NetPeer netPeer, NetConnection connection) { timeSinceStatusUpdate += (float)gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceStatusUpdate >= statusUpdateDelay) { timeSinceStatusUpdate = 0f; if (Team == Player.Me.Team) { NetOutgoingMessage msg = netPeer.CreateMessage(); msg.Write(MessageID.UNIT_STATUS_UPDATE); msg.Write(ID); msg.Write(Team); msg.Write((short)Hp); msg.Write(centerPoint.X); msg.Write(centerPoint.Y); msg.Write(Rotation); msg.Write(IsIdle); // send current command ID, -1 if none if (Commands.Count > 0) msg.Write(Commands[0].ID); else msg.Write((short)-1); // send cargoAmount, 0 if not worker WorkerNublet worker = this as WorkerNublet; if (worker != null) msg.Write(worker.CargoAmount); else msg.Write((short)0); netPeer.SendMessage(msg, connection, NetDeliveryMethod.ReliableOrdered); } else if (HpChanged) { HpChanged = false; NetOutgoingMessage msg = netPeer.CreateMessage(); msg.Write(MessageID.UNIT_HP_UPDATE); msg.Write(ID); msg.Write(Team); msg.Write((short)Hp); netPeer.SendMessage(msg, connection, NetDeliveryMethod.ReliableOrdered); } } }
protected override bool HandleMessage(NetPeer peer, NetIncomingMessage msg) { if (base.HandleMessage(peer, msg)) { return true; } switch (msg.MessageType) { case NetIncomingMessageType.DiscoveryRequest: { if (m_respondsToDiscovery) { NetOutgoingMessage message = peer.CreateMessage(); PostNotificationImmediately(NetworkNotifications.LocalClientDiscovered, message); peer.SendDiscoveryResponse(message, msg.SenderEndPoint); return true; } return false; } } return false; }
public static void RequestNATIntroduction(IPEndPoint host, NetPeer peer) { if (host == null) return; if (MonoGamerPeer.m_masterServer == null) throw new Exception("Must connect to master server first!"); NetOutgoingMessage message = peer.CreateMessage(); message.Write((byte) 2); IPAddress address = IPAddress.Parse(MonoGamerPeer.GetMyLocalIpAddress()); message.Write(new IPEndPoint(address, peer.get_Port())); IPEndPoint ipEndPoint = new IPEndPoint(host.Address, MonoGamerPeer.port); message.Write(ipEndPoint); message.Write(peer.get_Configuration().get_AppIdentifier()); peer.SendUnconnectedMessage(message, MonoGamerPeer.m_masterServer); }
static void Main(string[] args) { List<IPEndPoint[]> registeredHosts = new List<IPEndPoint[]>(); NetPeerConfiguration config = new NetPeerConfiguration("masterserver"); config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true); config.Port = CommonConstants.MasterServerPort; NetPeer peer = new NetPeer(config); peer.Start(); // keep going until ESCAPE is pressed Console.WriteLine("Press ESC to quit"); while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape) { NetIncomingMessage msg; while((msg = peer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.UnconnectedData: // // We've received a message from a client or a host // // by design, the first byte always indicates action switch ((MasterServerMessageType)msg.ReadByte()) { case MasterServerMessageType.RegisterHost: // It's a host wanting to register its presence IPEndPoint[] eps = new IPEndPoint[] { msg.ReadIPEndpoint(), // internal msg.SenderEndpoint // external }; Console.WriteLine("Got registration for host " + eps[1]); registeredHosts.Add(eps); break; case MasterServerMessageType.RequestHostList: // It's a client wanting a list of registered hosts Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndpoint); foreach (IPEndPoint[] ep in registeredHosts) { // send registered host to client NetOutgoingMessage om = peer.CreateMessage(); om.Write(ep[0]); om.Write(ep[1]); peer.SendUnconnectedMessage(om, msg.SenderEndpoint); } break; case MasterServerMessageType.RequestIntroduction: // It's a client wanting to connect to a specific (external) host IPEndPoint clientInternal = msg.ReadIPEndpoint(); IPEndPoint hostExternal = msg.ReadIPEndpoint(); string token = msg.ReadString(); Console.WriteLine(msg.SenderEndpoint + " requesting introduction to " + hostExternal + " (token " + token + ")"); // find in list foreach (IPEndPoint[] elist in registeredHosts) { if (elist[1].Equals(hostExternal)) { // found in list - introduce client and host to eachother Console.WriteLine("Sending introduction..."); peer.Introduce( elist[0], // host internal elist[1], // host external clientInternal, // client internal msg.SenderEndpoint, // client external token // request token ); break; } } break; } break; case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: // print diagnostics message Console.WriteLine(msg.ReadString()); break; } } } peer.Shutdown("shutting down"); }
public static void SendMessage(NetPeer peer, NetworkMessageType networkMessageType, int data, NetConnection recipient) { NetOutgoingMessage message = peer.CreateMessage(); message.Write((byte)networkMessageType); message.Write(data, 32); peer.SendMessage(message, recipient, NetDeliveryMethod.ReliableUnordered); }
public static void SendMCS() { Console.WriteLine("Enter Port: "); int port = int.Parse(Console.ReadLine()); NetPeerConfiguration config = new NetPeerConfiguration("InduZtry"); config.Port = port; config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); config.EnableMessageType(NetIncomingMessageType.Data); //config.EnableUPnP = true; server = new NetPeer(config); server.Start(); //Console.WriteLine(server.UPnP.Status); //server.UPnP.ForwardPort(port, "InduZtry"); //Console.WriteLine(server.UPnP.Status); //Console.WriteLine("UPnP IP: " + server.UPnP.GetExternalIP()); Thread t = new Thread(RecvMCS); t.IsBackground = true; t.Start(); message = "NULL"; while(true) { Thread.Sleep(10); if(recipient != null) { NetOutgoingMessage sendMsg = server.CreateMessage(); sendMsg.Write(message); server.SendMessage(sendMsg, recipient, NetDeliveryMethod.ReliableOrdered); } } }
public static void Run(NetPeer peer) { // // Test XTEA // NetXtea xtea = new NetXtea("TopSecret"); byte[] original = new byte[16]; NetRandom.Instance.NextBytes(original); byte[] encrypted = new byte[original.Length]; xtea.EncryptBlock(original, 0, encrypted, 0); xtea.EncryptBlock(original, 8, encrypted, 8); byte[] decrypted = new byte[original.Length]; xtea.DecryptBlock(encrypted, 0, decrypted, 0); xtea.DecryptBlock(encrypted, 8, decrypted, 8); // compare! for (int i = 0; i < original.Length; i++) if (original[i] != decrypted[i]) throw new NetException("XTEA fail!"); Console.WriteLine("XTEA OK"); NetOutgoingMessage om = peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); om.Encrypt(xtea); // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits); im.Decrypt(xtea); if (im.ReadString() != "Hallon") throw new NetException("fail"); if (im.ReadInt32() != 42) throw new NetException("fail"); if (im.ReadInt32(5) != 5) throw new NetException("fail"); if (im.ReadBoolean() != true) throw new NetException("fail"); if (im.ReadString() != "kokos") throw new NetException("fail"); for (int i = 0; i < 100; i++) { byte[] salt = NetSRP.CreateRandomSalt(); byte[] x = NetSRP.ComputePrivateKey("user", "password", salt); byte[] v = NetSRP.ComputeServerVerifier(x); //Console.WriteLine("v = " + NetUtility.ToHexString(v)); byte[] a = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("393ed364924a71ba7258633cc4854d655ca4ec4e8ba833eceaad2511e80db2b5"); byte[] A = NetSRP.ComputeClientEphemeral(a); //Console.WriteLine("A = " + NetUtility.ToHexString(A)); byte[] b = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("cc4d87a90db91067d52e2778b802ca6f7d362490c4be294b21b4a57c71cf55a9"); byte[] B = NetSRP.ComputeServerEphemeral(b, v); //Console.WriteLine("B = " + NetUtility.ToHexString(B)); byte[] u = NetSRP.ComputeU(A, B); //Console.WriteLine("u = " + NetUtility.ToHexString(u)); byte[] Ss = NetSRP.ComputeServerSessionValue(A, v, u, b); //Console.WriteLine("Ss = " + NetUtility.ToHexString(Ss)); byte[] Sc = NetSRP.ComputeClientSessionValue(B, x, u, a); //Console.WriteLine("Sc = " + NetUtility.ToHexString(Sc)); if (Ss.Length != Sc.Length) throw new NetException("SRP non matching lengths!"); for (int j = 0; j < Ss.Length; j++) { if (Ss[j] != Sc[j]) throw new NetException("SRP non matching session values!"); } var test = NetSRP.CreateEncryption(Ss); } Console.WriteLine("Message encryption OK"); }
public void CheckForStatusUpdate(GameTime gameTime, NetPeer netPeer, NetConnection connection) { timeSinceStatusUpdate += (float)gameTime.ElapsedGameTime.TotalSeconds; if (HpChanged && timeSinceStatusUpdate >= statusUpdateDelay) { timeSinceStatusUpdate = 0f; HpChanged = false; NetOutgoingMessage msg = netPeer.CreateMessage(); msg.Write(MessageID.STRUCTURE_STATUS_UPDATE); msg.Write(ID); msg.Write(Team); msg.Write((short)Hp); netPeer.SendMessage(msg, connection, NetDeliveryMethod.ReliableOrdered); } }
public void checkForStatusUpdate(NetPeer netPeer, NetConnection connection, int team) { if (AmountChanged && ((team == Player.Me.Team && timeSinceStatusUpdate >= statusUpdateDelay) || Depleted)) { timeSinceStatusUpdate = 0f; AmountChanged = false; NetOutgoingMessage msg = netPeer.CreateMessage(); msg.Write(MessageID.RESOURCE_STATUS_UPDATE); msg.Write(ID); msg.Write((short)Amount); netPeer.SendMessage(msg, connection, NetDeliveryMethod.ReliableOrdered); } }
public static void Run(NetPeer peer) { // // Test encryption // List<NetEncryption> algos = new List<NetEncryption>(); algos.Add(new NetXorEncryption(peer, "TopSecret")); algos.Add(new NetXtea(peer, "TopSecret")); algos.Add(new NetAESEncryption(peer, "TopSecret")); algos.Add(new NetRC2Encryption(peer, "TopSecret")); algos.Add(new NetDESEncryption(peer, "TopSecret")); algos.Add(new NetTripleDESEncryption(peer, "TopSecret")); foreach (var algo in algos) { NetOutgoingMessage om = peer.CreateMessage(); om.Write("Hallon"); om.Write(42); om.Write(5, 5); om.Write(true); om.Write("kokos"); int unencLen = om.LengthBits; om.Encrypt(algo); // convert to incoming message NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits); if (im.Data == null || im.Data.Length == 0) throw new NetException("bad im!"); im.Decrypt(algo); if (im.Data == null || im.Data.Length == 0 || im.LengthBits != unencLen) throw new NetException("Length fail"); var str = im.ReadString(); if (str != "Hallon") throw new NetException("fail"); if (im.ReadInt32() != 42) throw new NetException("fail"); if (im.ReadInt32(5) != 5) throw new NetException("fail"); if (im.ReadBoolean() != true) throw new NetException("fail"); if (im.ReadString() != "kokos") throw new NetException("fail"); Console.WriteLine(algo.GetType().Name + " encryption verified"); } for (int i = 0; i < 100; i++) { byte[] salt = NetSRP.CreateRandomSalt(); byte[] x = NetSRP.ComputePrivateKey("user", "password", salt); byte[] v = NetSRP.ComputeServerVerifier(x); //Console.WriteLine("v = " + NetUtility.ToHexString(v)); byte[] a = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("393ed364924a71ba7258633cc4854d655ca4ec4e8ba833eceaad2511e80db2b5"); byte[] A = NetSRP.ComputeClientEphemeral(a); //Console.WriteLine("A = " + NetUtility.ToHexString(A)); byte[] b = NetSRP.CreateRandomEphemeral(); // NetUtility.ToByteArray("cc4d87a90db91067d52e2778b802ca6f7d362490c4be294b21b4a57c71cf55a9"); byte[] B = NetSRP.ComputeServerEphemeral(b, v); //Console.WriteLine("B = " + NetUtility.ToHexString(B)); byte[] u = NetSRP.ComputeU(A, B); //Console.WriteLine("u = " + NetUtility.ToHexString(u)); byte[] Ss = NetSRP.ComputeServerSessionValue(A, v, u, b); //Console.WriteLine("Ss = " + NetUtility.ToHexString(Ss)); byte[] Sc = NetSRP.ComputeClientSessionValue(B, x, u, a); //Console.WriteLine("Sc = " + NetUtility.ToHexString(Sc)); if (Ss.Length != Sc.Length) throw new NetException("SRP non matching lengths!"); for (int j = 0; j < Ss.Length; j++) { if (Ss[j] != Sc[j]) throw new NetException("SRP non matching session values!"); } var test = NetSRP.CreateEncryption(peer, Ss); } Console.WriteLine("Message encryption OK"); }
/// <summary> /// Подключение к P2P сервису. Для создания UDP окна. /// </summary> /// <param name="remotePoint">Адрес сервиса.</param> internal void ConnectToService(IPEndPoint remotePoint) { ThrowIfDisposed(); if (Interlocked.CompareExchange(ref state, (int)PeerState.ConnectedToService, (int)PeerState.NotConnected) != (int)PeerState.NotConnected) throw new InvalidOperationException("Peer has not right state."); if (handler != null && handler.Status == NetPeerStatus.Running) throw new ArgumentException("Already runned."); var config = new NetPeerConfiguration(NetConfigString); config.Port = 0; config.AcceptIncomingConnections = true; config.EnableMessageType(NetIncomingMessageType.ConnectionApproval); if (remotePoint.AddressFamily == AddressFamily.InterNetworkV6) config.LocalAddress = IPAddress.IPv6Any; handler = new NetPeer(config); syncContext.Send(p => ((NetPeer)p).RegisterReceivedCallback(ReceivedCallback), handler); handler.Start(); var hailMessage = handler.CreateMessage(); using (var client = ClientModel.Get()) { var localPoint = new IPEndPoint(Connection.GetIPAddress(remotePoint.AddressFamily), handler.Port); hailMessage.Write(client.User.Nick); hailMessage.Write(localPoint); } serviceConnection = handler.Connect(remotePoint, hailMessage); ClientModel.Logger.WriteDebug("AsyncPeer.ConnectToService({0})", remotePoint); }
static void Main(string[] args) { Console.WriteLine("Server Started"); Dictionary<IPEndPoint, AvailableGame> registeredHosts = new Dictionary<IPEndPoint, AvailableGame>(); NetPeerConfiguration config = new NetPeerConfiguration("masterserver"); config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true); config.Port = 6000; NetPeer peer = new NetPeer(config); peer.Start(); // keep going until ESCAPE is pressed Console.WriteLine("Press ESC to quit"); while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape) { System.Threading.Thread.Sleep(10); NetIncomingMessage msg; while ((msg = peer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.UnconnectedData: // // We've received a message from a client or a host // // by design, the first byte always indicates action switch (msg.ReadByte()) { case 0: // register a new game // currently only one game per host per router. if (!registeredHosts.ContainsKey(msg.SenderEndpoint)) { AvailableGame game = new AvailableGame(); game.Count = msg.ReadInt32(); game.GamerTag = msg.ReadString(); game.PrivateGamerSlots = msg.ReadInt32(); game.MaxGamers = msg.ReadInt32(); game.IsHost = msg.ReadBoolean(); game.InternalIP = msg.ReadIPEndpoint(); game.ExternalIP = msg.SenderEndpoint; game.Game = msg.ReadString(); Console.WriteLine("Got registration for host " + game.ToString()); registeredHosts.Add(game.ExternalIP, game); } break; case 1: // It's a client wanting a list of registered hosts Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndpoint); string appid = msg.ReadString(); foreach (AvailableGame g1 in registeredHosts.Values) { if (g1.Game == appid) { // send registered host to client NetOutgoingMessage om = peer.CreateMessage(); om.Write(g1.Count); om.Write(g1.GamerTag); om.Write(g1.PrivateGamerSlots); om.Write(g1.MaxGamers); om.Write(g1.IsHost); om.Write(g1.InternalIP); om.Write(g1.ExternalIP); peer.SendUnconnectedMessage(om, msg.SenderEndpoint); } } break; case 2: // It's a client wanting to connect to a specific (external) host IPEndPoint clientInternal = msg.ReadIPEndpoint(); IPEndPoint hostExternal = msg.ReadIPEndpoint(); string token = msg.ReadString(); Console.WriteLine(msg.SenderEndpoint + " requesting introduction to " + hostExternal + " (token " + token + ")"); // find in list foreach (AvailableGame elist in registeredHosts.Values) { if (elist.ExternalIP.Equals(hostExternal)) { // found in list - introduce client and host to eachother Console.WriteLine("Sending introduction..."); peer.Introduce( elist.InternalIP, // host internal elist.ExternalIP, // host external clientInternal, // client internal msg.SenderEndpoint, // client external token // request token ); break; } } break; case 3: if (registeredHosts.ContainsKey(msg.SenderEndpoint)) { AvailableGame game = registeredHosts[msg.SenderEndpoint]; string tag = msg.ReadString(); string gamename = msg.ReadString(); if (game.GamerTag == tag) { Console.WriteLine("Remove for host " + game.ExternalIP.ToString()); registeredHosts.Remove(game.ExternalIP); } } break; case 4 : if (registeredHosts.ContainsKey(msg.SenderEndpoint)) { AvailableGame game = registeredHosts[msg.SenderEndpoint]; int count = msg.ReadInt32(); string tag = msg.ReadString(); if (game.GamerTag == tag) { Console.WriteLine("Update for host " + game.ExternalIP.ToString()); game.Count = count; game.PrivateGamerSlots = msg.ReadInt32(); game.MaxGamers = msg.ReadInt32(); game.IsHost = msg.ReadBoolean(); game.InternalIP = msg.ReadIPEndpoint(); game.Game = msg.ReadString(); } } break; } break; case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: // print diagnostics message Console.WriteLine(msg.ReadString()); break; } } } peer.Shutdown("shutting down"); }
private void Send(NetPeer peer, NetConnection destination, NetDeliveryMethod method) { NetOutgoingMessage nom = peer.CreateMessage(InitialMessageSize()); nom.Write(this.GetType().FullName); this.WriteData(nom); peer.SendMessage(nom, destination, method); }
public static void Run(NetPeer peer) { NetOutgoingMessage msg = peer.CreateMessage(); msg.Write(false); msg.Write(-3, 6); msg.Write(42); msg.Write("duke of earl"); msg.Write((byte)43); msg.Write((ushort)44); msg.Write(true); msg.WritePadBits(); int bcnt = 0; msg.Write(45.0f); msg.Write(46.0); bcnt += msg.WriteVariableInt32(-47); msg.WriteVariableInt32(470000); msg.WriteVariableUInt32(48); bcnt += msg.WriteVariableInt64(-49); if (bcnt != 2) throw new NetException("WriteVariable* wrote too many bytes!"); byte[] data = msg.PeekDataBuffer(); NetIncomingMessage inc = Program.CreateIncomingMessage(data, msg.LengthBits); StringBuilder bdr = new StringBuilder(); bdr.Append(inc.ReadBoolean()); bdr.Append(inc.ReadInt32(6)); bdr.Append(inc.ReadInt32()); bdr.Append(inc.ReadString()); bdr.Append(inc.ReadByte()); if (inc.PeekUInt16() != (ushort)44) throw new NetException("Read/write failure"); bdr.Append(inc.ReadUInt16()); bdr.Append(inc.ReadBoolean()); inc.SkipPadBits(); bdr.Append(inc.ReadSingle()); bdr.Append(inc.ReadDouble()); bdr.Append(inc.ReadVariableInt32()); bdr.Append(inc.ReadVariableInt32()); bdr.Append(inc.ReadVariableUInt32()); bdr.Append(inc.ReadVariableInt64()); if (bdr.ToString().Equals("False-342duke of earl4344True4546-4747000048-49")) Console.WriteLine("Read/write tests OK"); else throw new NetException("Read/write tests FAILED!"); msg = peer.CreateMessage(); NetOutgoingMessage tmp = peer.CreateMessage(); tmp.Write((int)42, 14); msg.Write(tmp); msg.Write(tmp); if (msg.LengthBits != tmp.LengthBits * 2) throw new NetException("NetOutgoingMessage.Write(NetOutgoingMessage) failed!"); tmp = peer.CreateMessage(); Test test = new Test(); test.Number = 42; test.Name = "Hallon"; test.Age = 8.2f; tmp.WriteAllFields(test, BindingFlags.Public | BindingFlags.Instance); data = tmp.PeekDataBuffer(); inc = Program.CreateIncomingMessage(data, tmp.LengthBits); Test readTest = new Test(); inc.ReadAllFields(readTest, BindingFlags.Public | BindingFlags.Instance); NetException.Assert(readTest.Number == 42); NetException.Assert(readTest.Name == "Hallon"); NetException.Assert(readTest.Age == 8.2f); // test aligned WriteBytes/ReadBytes msg = peer.CreateMessage(); byte[] tmparr = new byte[] { 5, 6, 7, 8, 9 }; msg.Write(tmparr); inc = Program.CreateIncomingMessage(msg.PeekDataBuffer(), msg.LengthBits); byte[] result = inc.ReadBytes(tmparr.Length); for (int i = 0; i < tmparr.Length; i++) if (tmparr[i] != result[i]) throw new Exception("readbytes fail"); }
static void Main(string[] args) { Dictionary<long, ServerData> registeredHosts = new Dictionary<long, ServerData>(); NetPeerConfiguration config = new NetPeerConfiguration("masterserver"); config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true); config.Port = SharedConfiguration.MasterServerEndPoint.Port; NetPeer peer = new NetPeer(config); peer.Start(); // keep going until ESCAPE is pressed Console.WriteLine("Press ESC to quit"); while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape) { NetIncomingMessage msg; while ((msg = peer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.UnconnectedData: // // We've received a message from a client or a host // // by design, the first byte always indicates action switch ((MasterServerMessageType)msg.ReadByte()) { case MasterServerMessageType.RegisterHost: // It's a host wanting to register its presence var id = msg.ReadInt64(); // server unique identifier Console.WriteLine("Got registration for host " + id); ServerData serverData = new ServerData(); serverData.IPEndPoint[0] = msg.ReadIPEndPoint(); serverData.IPEndPoint[1] = msg.SenderEndPoint; serverData.ServerName = msg.ReadString(); serverData.ScriptName = msg.ReadString(); serverData.Players = msg.ReadInt32(); serverData.MaxPlayers = msg.ReadInt32(); registeredHosts[id] = serverData; break; case MasterServerMessageType.RequestHostList: // It's a client wanting a list of registered hosts Console.WriteLine("Sending list of " + registeredHosts.Count + " hosts to client " + msg.SenderEndPoint); foreach (var kvp in registeredHosts) { // send registered host to client NetOutgoingMessage om = peer.CreateMessage(); om.Write(kvp.Key); om.Write(kvp.Value.IPEndPoint[0]); om.Write(kvp.Value.IPEndPoint[1]); om.Write(kvp.Value.ServerName); om.Write(kvp.Value.ScriptName); om.Write(kvp.Value.Players); om.Write(kvp.Value.MaxPlayers); peer.SendUnconnectedMessage(om, msg.SenderEndPoint); } break; } break; case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: // print diagnostics message Console.WriteLine(msg.ReadString()); break; } } } peer.Shutdown("shutting down"); }
/// <summary> /// Contacts the Master Server on the net and gets a list of available host games /// </summary> /// <param name="netPeer"></param> private static void GetServerList (NetPeer netPeer) { m_masterServer = new IPEndPoint (NetUtility.Resolve (masterServer), masterserverport); NetOutgoingMessage listRequest = netPeer.CreateMessage (); listRequest.Write ((byte)1); listRequest.Write (netPeer.Configuration.AppIdentifier); netPeer.SendUnconnectedMessage (listRequest, m_masterServer); }
private static void GetServerList(NetPeer netPeer) { MonoGamerPeer.m_masterServer = new IPEndPoint(NetUtility.Resolve(MonoGamerPeer.masterServer), MonoGamerPeer.masterserverport); NetOutgoingMessage message = netPeer.CreateMessage(); message.Write((byte) 1); message.Write(netPeer.get_Configuration().get_AppIdentifier()); netPeer.SendUnconnectedMessage(message, MonoGamerPeer.m_masterServer); }