Пример #1
0
        public override SocketTasks StartClient()
        {
            SocketConfig config = GetConfig(false, NetworkingManager.Singleton.NetworkConfig);

            socket = new RuffleSocket(config);

            isConnector = true;

            if (!socket.Start())
            {
                return(SocketTask.Fault.AsTasks());
            }

            serverConnection = socket.Connect(new IPEndPoint(IPAddress.Parse(ConnectAddress), Port));

            if (serverConnection == null)
            {
                return(SocketTask.Fault.AsTasks());
            }
            else
            {
                connectTask = SocketTask.Working;

                return(connectTask.AsTasks());
            }
        }
Пример #2
0
        public bool Connect(IPEndPoint endPoint)
        {
            socket = new RuffleSocket(new SocketConfig
            {
                ChallengeDifficulty = 20,
                ChannelTypes        = new[]
                {
                    ChannelType.ReliableSequencedFragmented
                },
                DualListenPort = 0
            });

            if (!socket.Start())
            {
                return(false);
            }

            var con = socket.Connect(endPoint);

            if (con != null)
            {
                return(true);
            }

            return(false);
        }
Пример #3
0
        public static void Server()
        {
            RuffleSocket socket = new RuffleSocket(new Configuration.SocketConfig()
            {
                AllowBroadcasts          = true,
                AllowUnconnectedMessages = true,
                DualListenPort           = 5555
            });

            socket.Start();

            while (true)
            {
                // Wait for message. This is to prevent a tight loop
                socket.SyncronizationEvent.WaitOne(1000);

                NetworkEvent @event;
                while ((@event = socket.Poll()).Type != NetworkEventType.Nothing)
                {
                    if (@event.Type == NetworkEventType.BroadcastData)
                    {
                        // We got a broadcast. Reply to them with the same token they used
                        socket.SendUnconnected(@event.Data, (IPEndPoint)@event.EndPoint);
                    }

                    // Recycle the event
                    @event.Recycle();
                }
            }
        }
Пример #4
0
        public override void StartServer()
        {
            SocketConfig config = GetConfig();

            config.DualListenPort = (ushort)ServerListenPort;

            socket = new RuffleSocket(config);
        }
        public override SocketTasks StartServer()
        {
            SocketConfig config = GetConfig();

            config.DualListenPort = (ushort)ServerListenPort;

            socket = new RuffleSocket(config);

            return(SocketTask.Done.AsTasks());
        }
Пример #6
0
        internal Connection(ulong id, ConnectionState state, IPEndPoint endpoint, RuffleSocket socket)
        {
#if ALLOW_CONNECTION_STUB
            if (IsStub)
            {
                // NOOP
                return;
            }
#endif
            this.Id                              = id;
            this.Socket                          = socket;
            this.EndPoint                        = endpoint;
            this.MTU                             = Config.MinimumMTU;
            this.SmoothRoundtrip                 = 0;
            this.HighestRoundtripVarience        = 0;
            this.Roundtrip                       = 500;
            this.LowestRoundtrip                 = 500;
            this.LastMessageIn                   = NetTime.Now;
            this.LastMessageOut                  = NetTime.Now;
            this.ConnectionStarted               = NetTime.Now;
            this.ConnectionCompleted             = NetTime.Now;
            this.HandshakeStarted                = NetTime.Now;
            this.HandshakeLastSendTime           = NetTime.Now;
            this.HandshakeResendAttempts         = 0;
            this.ChallengeAnswer                 = 0;
            this.ConnectionChallenge             = RandomProvider.GetRandomULong();
            this.ChallengeDifficulty             = (byte)Config.ChallengeDifficulty;
            this.PreConnectionChallengeTimestamp = 0;
            this.PreConnectionChallengeCounter   = 0;
            this.PreConnectionChallengeIV        = 0;
            this.PreConnectionChallengeSolved    = false;
            this.State                           = state;

            if (Config.EnableBandwidthTracking && Config.CreateBandwidthTracker != null)
            {
                this.BandwidthTracker = Config.CreateBandwidthTracker();
            }

            if (Config.EnableHeartbeats)
            {
                this.HeartbeatChannel = new UnreliableOrderedChannel(0, this, Config, MemoryManager);
            }

            if (Config.EnablePacketMerging)
            {
                this.Merger = new MessageMerger(Config.MaxMergeMessageSize, Config.MinimumMTU);
            }

            if (Logging.CurrentLogLevel <= LogLevel.Debug)
            {
                Logging.LogInfo("Allocating " + Config.EventQueueSize + " event slots");
            }
            this._userEventQueue        = new ConcurrentCircularQueue <NetworkEvent>(Config.EventQueueSize, true);
            this.IsUserEventQueueActive = true;
        }
        internal ReliableSequencedChannel(byte channelId, Connection connection, RuffleSocket socket, SocketConfig config)
        {
            this.channelId  = channelId;
            this.connection = connection;
            this.socket     = socket;
            this.config     = config;

            // Alloc the in flight windows for receive and send
            _receiveSequencer = new HeapableSlidingWindow <PendingIncomingPacket>(config.ReliabilityWindowSize, true, sizeof(ushort));
            _sendSequencer    = new HeapableSlidingWindow <PendingOutgoingPacket>(config.ReliabilityWindowSize, true, sizeof(ushort));
        }
Пример #8
0
        public override void StartClient()
        {
            SocketConfig config = GetConfig();

            // The OS will grab a port
            config.DualListenPort = 0;
            socket = new RuffleSocket(config);

            isConnector = true;
            socket.Connect(new IPEndPoint(IPAddress.Parse(ConnectAddress), ConnectPort));
        }
Пример #9
0
        public override bool StartServer()
        {
            SocketConfig config = GetConfig(true);

            socket = new RuffleSocket(config);

            serverConnection = null;
            isConnector      = false;

            return(socket.Start());
        }
Пример #10
0
        public Task Run()
        {
            _server = new RuffleSocket(_serverConfig);
            _server.Start();

            return(Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Update();
                }
            }, TaskCreationOptions.LongRunning));
        }
Пример #11
0
        public Client(Scene scene, List<ISystem<ClientSystemUpdate>> clientSystems, Dictionary<int, Action<MemoryStream, World>> recievers, Dictionary<Type, Action<object, MemoryStream>> serializers)
            : base(scene, recievers, serializers)
        {
            _clientSystems = clientSystems;
            _camerasSet = scene.World.GetEntities().With<Transform>().With<Camera>().AsSet();

            _editorMenu = new EditorMenu();
            _editorMenu.Editors.Add(new ConstructEditor(scene.World));
            _editorMenu.Editors.Add(new InfoViewer());

            _client = new RuffleSocket(_clientConfig);
            _messageTimer = new Stopwatch();
        }
Пример #12
0
        internal Connection(ulong id, ConnectionState state, IPEndPoint endpoint, RuffleSocket socket)
        {
#if ALLOW_CONNECTION_STUB
            if (IsStub)
            {
                // NOOP
                return;
            }
#endif
            this.Id                              = id;
            this.Socket                          = socket;
            this.EndPoint                        = endpoint;
            this.MTU                             = Config.MinimumMTU;
            this.SmoothRoundtrip                 = 0;
            this.HighestRoundtripVarience        = 0;
            this.Roundtrip                       = 500;
            this.LowestRoundtrip                 = 500;
            this.LastMessageIn                   = NetTime.Now;
            this.LastMessageOut                  = NetTime.Now;
            this.ConnectionStarted               = NetTime.Now;
            this.ConnectionCompleted             = NetTime.Now;
            this.HandshakeStarted                = NetTime.Now;
            this.HandshakeLastSendTime           = NetTime.Now;
            this.HandshakeResendAttempts         = 0;
            this.ChallengeAnswer                 = 0;
            this.ConnectionChallenge             = RandomProvider.GetRandomULong();
            this.ChallengeDifficulty             = (byte)Config.ChallengeDifficulty;
            this.PreConnectionChallengeTimestamp = 0;
            this.PreConnectionChallengeCounter   = 0;
            this.PreConnectionChallengeIV        = 0;
            this.PreConnectionChallengeSolved    = false;
            this.State                           = state;

            if (Config.EnableBandwidthTracking && Config.CreateBandwidthTracker != null)
            {
                this.BandwidthTracker = Config.CreateBandwidthTracker();
            }

            if (Config.EnableHeartbeats)
            {
                this.HeartbeatChannel = new UnreliableOrderedChannel(0, this, Config, MemoryManager);
            }

            if (Config.EnablePacketMerging)
            {
                this.Merger = new MessageMerger(Config.MaxMergeMessageSize, Config.MinimumMTU, Config.MaxMergeDelay);
            }
        }
Пример #13
0
        /// <summary>
        /// Binds the UDP socket to the specified local endpoint.
        /// </summary>
        /// <param name="endpoint">The local endpoint to bind to.</param>
        public void Bind(IPEndPoint endpoint)
        {
            if (socket != null)
            {
                return;
            }
            // Setup the socket info here
            socket = new RuffleSocket(new SocketConfig()
            {
                AllowBroadcasts          = true, //necessary ?
                AllowUnconnectedMessages = true, //necessary ?
                DualListenPort           = endpoint.Port,
                IPv4ListenAddress        = endpoint.Address
            });

            socket.Start();
        }
Пример #14
0
        public override SocketTasks StartServer()
        {
            SocketConfig config = GetConfig(true, NetworkingManager.Singleton.NetworkConfig);

            socket = new RuffleSocket(config);

            serverConnection = null;
            isConnector      = false;

            if (socket.Start())
            {
                return(SocketTask.Done.AsTasks());
            }
            else
            {
                return(SocketTask.Fault.AsTasks());
            }
        }
Пример #15
0
        public bool Listen(int port)
        {
            socket = new RuffleSocket(new SocketConfig
            {
                ChallengeDifficulty = 20,
                IPv4ListenAddress   = IPAddress.Parse("0.0.0.0"),
                ChannelTypes        = new[]
                {
                    ChannelType.ReliableSequencedFragmented
                },
                DualListenPort = port,
            });

            var r = socket.Start();

            m_Address = new RuffleTransportAddress {
                EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)
            };
            return(r);
        }
Пример #16
0
        public override void Shutdown()
        {
            channelNameToId.Clear();
            connections.Clear();

            // Release to GC
            messageBuffer = null;

            if (socket != null && socket.IsInitialized)
            {
                // Releases memory and other things
                socket.Shutdown();
            }

            // Release to GC
            socket = null;

            // Release server connection to GC
            serverConnection = null;
        }
Пример #17
0
        public override bool StartClient()
        {
            SocketConfig config = GetConfig(false);

            socket = new RuffleSocket(config);

            isConnector = true;

            if (!socket.Start())
            {
                return(false);
            }

            serverConnection = socket.Connect(new IPEndPoint(IPAddress.Parse(ConnectAddress), Port));

            if (serverConnection == null)
            {
                return(false);
            }

            return(true);
        }
Пример #18
0
        /// <summary>
        /// Adds a local socket to the manager.
        /// </summary>
        /// <returns>The local socket.</returns>
        /// <param name="config">The socket configuration.</param>
        public RuffleSocket AddSocket(SocketConfig config)
        {
            if (!IsRunning)
            {
                throw new InvalidOperationException("Manager is not started");
            }

            RuffleSocket socket = new RuffleSocket(config);

            if (IsThreaded)
            {
                lock (ThreadLock)
                {
                    _sockets.Add(socket);
                }
            }
            else
            {
                _sockets.Add(socket);
            }

            return(socket);
        }
Пример #19
0
        public override void Start(object config)
        {
            RufflesConfig rufflesConfig = null;

            if (config is RufflesConfig)
            {
                rufflesConfig = (RufflesConfig)config;
            }
            else if (config is JObject)
            {
                rufflesConfig = ((JObject)config).ToObject <RufflesConfig>();
            }

            rufflesConfig.SocketConfig.DualListenPort = Program.Config.ListenPort;

            ChannelType[] channelTypes    = rufflesConfig.SocketConfig.ChannelTypes;
            ChannelType[] newChannelTypes = new ChannelType[channelTypes.Length + 1];

            // Copy old channels
            for (int i = 0; i < channelTypes.Length; i++)
            {
                newChannelTypes[i] = channelTypes[i];
            }

            // Set the default channel
            newChannelTypes[newChannelTypes.Length - 1] = rufflesConfig.DefaultChannelType;

            // Set the default channel byte
            Program.DEFAULT_CHANNEL_BYTE = (byte)(newChannelTypes.Length - 1);

            // Change to the new array
            rufflesConfig.SocketConfig.ChannelTypes = newChannelTypes;

            // Start the socket
            socket = new RuffleSocket((SocketConfig)config);
        }
Пример #20
0
        private static void NoRufflesManager()
        {
            RuffleSocket server = new RuffleSocket(ServerConfig);

            RuffleSocket client = new RuffleSocket(ClientConfig);

            // IPv4 Connect
            //client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5674));

            // IPv6 Connect
            client.Connect(new IPEndPoint(IPAddress.Parse("0:0:0:0:0:0:0:1"), 5674));

            // The server stores the clients id here
            ulong clientId = 0;
            // The client stores the servers id here
            ulong serverId = 0;

            // The time when the connection started
            DateTime started = DateTime.Now;

            // The time when the last message was sent
            DateTime lastSent = DateTime.MinValue;

            // The amount of message that has been received
            int messagesReceived = 0;

            // The amount of messages that has been sent
            int messageCounter = 0;

            while (true)
            {
                // Runs all the internals
                client.RunInternalLoop();
                // Runs all the internals
                server.RunInternalLoop();

                // Polls server for events
                NetworkEvent serverEvent = server.Poll();
                // Polls client for events
                NetworkEvent clientEvent = client.Poll();


                if (serverEvent.Type != NetworkEventType.Nothing)
                {
                    if (serverEvent.Type != NetworkEventType.Data)
                    {
                        Console.WriteLine("ServerEvent: " + serverEvent.Type);
                    }

                    if (serverEvent.Type == NetworkEventType.Connect)
                    {
                        clientId = serverEvent.Connection.Id;
                    }

                    if (serverEvent.Type == NetworkEventType.Disconnect || serverEvent.Type == NetworkEventType.Timeout)
                    {
                        serverEvent.Connection.Recycle();
                    }
                }

                if (clientEvent.Type != NetworkEventType.Nothing)
                {
                    if (clientEvent.Type != NetworkEventType.Data)
                    {
                        Console.WriteLine("ClientEvent: " + clientEvent.Type);
                    }

                    if (clientEvent.Type == NetworkEventType.Connect)
                    {
                        serverId = clientEvent.Connection.Id;
                    }

                    if (clientEvent.Type == NetworkEventType.Data)
                    {
                        messagesReceived++;
                        Console.WriteLine("Got message: \"" + Encoding.ASCII.GetString(clientEvent.Data.Array, clientEvent.Data.Offset, clientEvent.Data.Count) + "\"");
                        clientEvent.Recycle();
                    }

                    if (clientEvent.Type == NetworkEventType.Disconnect || clientEvent.Type == NetworkEventType.Timeout)
                    {
                        clientEvent.Connection.Recycle();
                    }
                }

                if ((DateTime.Now - started).TotalSeconds > 10 && (DateTime.Now - lastSent).TotalSeconds >= 1)
                {
                    byte[] helloReliable          = Encoding.ASCII.GetBytes("This message was sent over a reliable channel" + messageCounter);
                    byte[] helloReliableSequenced = Encoding.ASCII.GetBytes("This message was sent over a reliable sequenced channel" + messageCounter);

                    server.Send(new ArraySegment <byte>(helloReliableSequenced, 0, helloReliableSequenced.Length), clientId, 0, false);
                    server.Send(new ArraySegment <byte>(helloReliable, 0, helloReliable.Length), clientId, 1, false);

                    messageCounter++;
                    lastSent = DateTime.Now;
                }
            }
        }
Пример #21
0
        public static void Client()
        {
            RuffleSocket socket = new RuffleSocket(new Configuration.SocketConfig()
            {
                AllowBroadcasts          = true,
                AllowUnconnectedMessages = true,
                DualListenPort           = 0
            });

            socket.Start();

            // Wait for message. This is to prevent a tight loop
            socket.SyncronizationEvent.WaitOne(1000);

            // Create RNG
            System.Random rnd = new System.Random();
            // Alloc token
            byte[] token = new byte[32];
            // Fill buffer with random data
            rnd.NextBytes(token);

            // Save last send time
            DateTime lastBroadcastSendTime = DateTime.MinValue;

            while (true)
            {
                // If we havent sent broadcast for 5 seconds
                if ((DateTime.Now - lastBroadcastSendTime).TotalSeconds > 5)
                {
                    lastBroadcastSendTime = DateTime.Now;

                    // Send broadcast
                    socket.SendBroadcast(new ArraySegment <byte>(token), 5555);
                }

                // Wait for message. This is to prevent a tight loop
                socket.SyncronizationEvent.WaitOne(1000);

                NetworkEvent @event;
                while ((@event = socket.Poll()).Type != NetworkEventType.Nothing)
                {
                    if (@event.Type == NetworkEventType.UnconnectedData)
                    {
                        // We got a reply. Ensure the token is correct
                        if (@event.Data.Count == token.Length)
                        {
                            bool missMatch = false;

                            // The token had the same length. Check all elements
                            for (int i = 0; i < @event.Data.Count; i++)
                            {
                                if (@event.Data.Array[@event.Data.Offset + i] != token[i])
                                {
                                    // This element did not match. Exit
                                    missMatch = true;
                                    break;
                                }
                            }

                            if (missMatch)
                            {
                                // Continue the receive loop the loop
                                continue;
                            }
                            else
                            {
                                // All matched.
                                Console.WriteLine("Found server at endpoint: " + ((IPEndPoint)@event.EndPoint));
                            }
                        }
                    }

                    // Recycle the event
                    @event.Recycle();
                }
            }
        }
Пример #22
0
        static void Main(string[] args)
        {
            //Get Ruffles socket from MLAPI

            RuffleSocket socket = new RuffleSocket(new SocketConfig()
            {
                AllowBroadcasts          = true, //necessary ?
                AllowUnconnectedMessages = true, //necessary ?
            });

            IUDPTransport rufflesTransport = new MLAPI.Puncher.Shared.RufflesUDPTransport(socket);

            Task listenTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    using (PuncherClient listenPeer = new PuncherClient(PUNCHER_SERVER_HOST, PUNCHER_SERVER_PORT)
                    {
                        Transport = rufflesTransport
                    })
                    {
                        System.Console.WriteLine("[LISTENER] Listening for single punch on our port 1234...");
                        IPEndPoint endpoint = listenPeer.ListenForSinglePunch(new IPEndPoint(IPAddress.Any, 1234));
                        System.Console.WriteLine("[LISTENER] Connector: " + endpoint + " punched through our NAT");
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e);
                }
            });

            // Wait a bit to make sure the listener has a chance to register.
            Thread.Sleep(1000);

            System.Console.Write("[CONNECTOR] Enter the address of the listener you want to punch: ");
            string address = System.Console.ReadLine();

            using (PuncherClient connectPeer = new PuncherClient(PUNCHER_SERVER_HOST, PUNCHER_SERVER_PORT)
            {
                Transport = rufflesTransport
            })
            {
                System.Console.WriteLine("[CONNECTOR] Punching...");

                if (connectPeer.TryPunch(IPAddress.Parse(address), out IPEndPoint connectResult))
                {
                    System.Console.WriteLine("[CONNECTOR] Punched through to peer: " + connectResult);
                }
                else
                {
                    System.Console.WriteLine("[CONNECTOR] Failed to punch");
                }

                // Prevent application from exiting before listener has ended
                listenTask.Wait();
            }

            // For the plebs
            System.Console.Read();
        }
Пример #23
0
 public RufflesUDPTransport(RuffleSocket rsock)
 {
     socket = rsock;
 }
Пример #24
0
        public static void Main(string[] args)
        {
            RuffleSocket server = new RuffleSocket(ServerConfig);

            RuffleSocket client = new RuffleSocket(ClientConfig);

            client.Start();
            server.Start();

            if (IPv6)
            {
                // IPv6 Connect
                client.Connect(new IPEndPoint(IPAddress.Parse("0:0:0:0:0:0:0:1"), 5674));
            }
            else
            {
                // IPv4 Connect
                client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5674));
            }

            // The server stores the clients id here
            Connection clientConnection = null;
            // The client stores the servers id here
            Connection serverConnection = null;

            // The time when the connection started
            DateTime started = DateTime.Now;

            // The time when the last message was sent
            DateTime lastSent = DateTime.MinValue;

            // The time the last status was printed
            DateTime lastStatusPrint = DateTime.MinValue;

            // The amount of message that has been received
            int messagesReceived = 0;

            // The amount of messages that has been sent
            int messageCounter = 0;

            while (true)
            {
                // Polls server for events
                NetworkEvent serverEvent = server.Poll();
                // Polls client for events
                NetworkEvent clientEvent = client.Poll();

                if (serverEvent.Type != NetworkEventType.Nothing)
                {
                    Console.WriteLine("ServerEvent: " + serverEvent.Type);

                    if (serverEvent.Type == NetworkEventType.Connect)
                    {
                        clientConnection = serverEvent.Connection;
                    }

                    if (serverEvent.Type == NetworkEventType.AckNotification)
                    {
                        Console.WriteLine("The remote acked message id: " + serverEvent.NotificationKey);
                    }
                }

                serverEvent.Recycle();

                if (clientEvent.Type != NetworkEventType.Nothing)
                {
                    Console.WriteLine("ClientEvent: " + clientEvent.Type);

                    if (clientEvent.Type == NetworkEventType.Connect)
                    {
                        serverConnection = clientEvent.Connection;
                    }

                    if (clientEvent.Type == NetworkEventType.Data)
                    {
                        messagesReceived++;
                        Console.WriteLine("Got message: \"" + Encoding.ASCII.GetString(clientEvent.Data.Array, clientEvent.Data.Offset, clientEvent.Data.Count) + "\"");
                    }
                }

                clientEvent.Recycle();

                if (serverConnection != null && clientConnection != null && serverConnection.State == ConnectionState.Connected && clientConnection.State == ConnectionState.Connected && (DateTime.Now - lastSent).TotalSeconds >= (1f / 1))
                {
                    byte[] helloReliable = Encoding.ASCII.GetBytes("This message was sent over a reliable channel" + messageCounter);
                    clientConnection.Send(new ArraySegment <byte>(helloReliable, 0, helloReliable.Length), 1, false, (ulong)messageCounter);
                    Console.WriteLine("Sending packet: " + messageCounter);

                    messageCounter++;
                    lastSent = DateTime.Now;
                }

                if (serverConnection != null && clientConnection != null && serverConnection.State == ConnectionState.Connected && clientConnection.State == ConnectionState.Connected && (DateTime.Now - lastStatusPrint).TotalSeconds >= 5)
                {
                    Console.WriteLine("Ping: " + serverConnection.SmoothRoundtrip + "ms, " + clientConnection.SmoothRoundtrip + "ms");
                    lastStatusPrint = DateTime.Now;
                }
            }
        }