Beispiel #1
0
        public void UdpIPv4ConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296, IPMode.IPv4)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    listener.Start();

                    connection.Connect();
                }
        }
        public void UdpIPv4ConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                }
        }
        public override async Task <bool> PushCommand(ExecuteCommand execCommand)
        {
            bool result = false;

            try
            {
                var device = execCommand?.Command?.Device;

                if (device != null)
                {
                    var start = MsgLogger.BeginTimeMeasure();

                    if (device.ChannelLocalHost != EltraUdpConnector.LocalHost)
                    {
#if _UDP
                        var udpConnection = ConnectionManager.GetConnection <UdpClientConnection>(CommandExecUuid);

                        if (udpConnection == null)
                        {
                            var udpServerConnection = new UdpClientConnection()
                            {
                                ChannelName = "ExecuteCommander",
                                UniqueId    = CommandExecUuid,
                                Url         = device.ChannelLocalHost
                            };

                            await ConnectionManager.Connect(udpServerConnection);
                        }
                        else if (udpConnection.Url != device.ChannelLocalHost)
                        {
                            udpConnection.Url = device.ChannelLocalHost;

                            await udpConnection.Connect();
                        }
#endif
                    }

                    if (ConnectionManager != null && ConnectionManager.IsConnected(CommandExecUuid))
                    {
                        if (await ConnectionManager.Send(CommandExecUuid, UserIdentity, execCommand))
                        {
                            result = true;
                        }
                    }

                    MsgLogger.EndTimeMeasure($"{GetType().Name} - PushCommand", start, $"push command='{execCommand.Command.Name}' to device='{device.Family}':0x{device.NodeId}");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - PushCommand", e);
            }

            return(result);
        }
Beispiel #4
0
        /**
         * Helper method that fetches a new Reliable message writer for the specified connection,
         * invokes the specified write method, then sends the resulting message to the server.
         * Any errors during message sending will be ignored.
         */
        public static void SendReliableMessage(this UdpClientConnection connection, Action <MessageWriter> write)
        {
            var writer = MessageWriter.Get(SendOption.Reliable);

            try
            {
                write(writer);
                connection.Send(writer);
            } catch { /* Ignored */ Console.Out.WriteLine("Oops"); }
            writer.Recycle();
        }
        public void UdpIPv6ConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.IPv6Any, 4296), IPMode.IPv6))
            {
                listener.Start();

                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), IPMode.IPv6))
                {
                    connection.Connect();
                }
            }
        }
        private void CreateConnection(IPAddress address, int port)
        {
            if (connection != null)
            {
                connection.DataReceived -= Connection_DataReceived;
                connection.Disconnected -= Connection_Disconnected;
            }

            connection = new UdpClientConnection(new System.Net.IPEndPoint(address, port));
            connection.DataReceived += Connection_DataReceived;
            connection.Disconnected += Connection_Disconnected;
        }
Beispiel #7
0
 public void Connect(IPAddress address, int port)
 {
     if (connecting)
     {
         return;
     }
     this.connecting = true;
     this.connection = new UdpClientConnection(new System.Net.IPEndPoint(address, port));
     this.connection.DataReceived += Connection_DataReceived;
     this.connection.Disconnected += Connection_Disconnected;
     this.connection.Connect();
 }
    public uint GetSenderID()
    {
        uint clientID = 0;
        UdpClientConnection udpClientConnection = udpConnection as UdpClientConnection;

        if (udpClientConnection != null)
        {
            clientID = udpClientConnection.ClientID;
        }

        return(clientID);
    }
Beispiel #9
0
        private void btnWakeUp_Click(object sender, EventArgs e)
        {
            using (UdpClientConnection client = new UdpClientConnection()) {
                client.NetworkStream = new NetworkStream();

                client.Open(System.Net.IPAddress.Broadcast, 9);
                client.Broadcast();

                byte[] buf = GetWakeUpPacket(edtMAC.Text);
                client.WriteBytes(buf, 0, buf.Length);
            }

            MessageBox.Show("Done");
        }
        public void UdpHandshakeTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296, IPMode.IPv4)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    listener.Start();

                    listener.NewConnection += delegate(object sender, NewConnectionEventArgs e)
                    {
                        Assert.IsTrue(Enumerable.SequenceEqual(e.HandshakeData, new byte[] { 1, 2, 3, 4, 5, 6 }));
                    };

                    connection.Connect(new byte[] { 1, 2, 3, 4, 5, 6 });
                }
        }
Beispiel #11
0
        // [TestMethod]
        public void StressTestOpeningConnections()
        {
            // Start a listener in another process, or even better,
            // adjust the target IP and start listening on another computer.
            var ep = new IPEndPoint(IPAddress.Loopback, 22023);

            Parallel.For(0, 10000,
                         new ParallelOptions {
                MaxDegreeOfParallelism = 64
            },
                         (i) => {
                var connection = new UdpClientConnection(ep);
                connection.KeepAliveInterval = 50;

                connection.Connect(new byte[5]);
            });
        }
Beispiel #12
0
        public void TcpDualModeConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(IPAddress.Any, 4296, IPMode.IPv4AndIPv6))
            {
                listener.Start();

                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    connection.Connect();
                }

                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4AndIPv6)))
                {
                    connection.Connect();
                }
            }
        }
Beispiel #13
0
        private static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            var writeHandshake = MessageWriter.Get(MessageType.Reliable);

            writeHandshake.Write(50516550);
            writeHandshake.Write("AeonLucid");

            var writeGameCreate = MessageWriter.Get(MessageType.Reliable);

            Message00HostGameC2S.Serialize(writeGameCreate, new GameOptionsData
            {
                MaxPlayers   = 4,
                NumImpostors = 2
            });

            // TODO: ObjectPool for MessageReaders
            using (var connection = new UdpClientConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22023), null))
            {
                var e = new ManualResetEvent(false);

                // Register events.
                connection.DataReceived = DataReceived;
                connection.Disconnected = Disconnected;

                // Connect and send handshake.
                await connection.ConnectAsync(writeHandshake.ToByteArray(false));

                Log.Information("Connected.");

                // Create a game.
                await connection.SendAsync(writeGameCreate);

                Log.Information("Requested game creation.");

                // Recycle.
                writeHandshake.Recycle();
                writeGameCreate.Recycle();

                e.WaitOne();
            }
        }
Beispiel #14
0
        //static string remoteHost = "172.26.187.156";
        //static string host = "172.26.187.156";

        public static async void ConnectHost(Object obj)
        {
            int port = (int)obj;
            UdpClientConnection conn = new UdpClientConnection(host, port, remoteHost, 1230);

            var connectOK = await conn.ConnectAsync();

            if (connectOK)
            {
                Console.WriteLine("Client");
                Thread.Sleep(1000);
                sendMsg(conn, port);
            }
            else
            {
                Console.WriteLine("client connect server failed");
            }
            conn.Close();
        }
        public void KeepAliveClientTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                    connection.KeepAliveInterval = 100;

                    System.Threading.Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.IsTrue(
                        connection.Statistics.TotalBytesSent >= 30 &&
                        connection.Statistics.TotalBytesSent <= 50,
                        "Sent: " + connection.Statistics.TotalBytesSent
                        );
                }
        }
        public void UdpFieldTest()
        {
            NetworkEndPoint ep = new NetworkEndPoint(IPAddress.Loopback, 4296);

            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(ep))
                {
                    listener.Start();

                    connection.Connect();

                    //Connection fields
                    Assert.AreEqual(ep, connection.EndPoint);

                    //UdpConnection fields
                    Assert.AreEqual(new IPEndPoint(IPAddress.Loopback, 4296), connection.RemoteEndPoint);
                    Assert.AreEqual(1, connection.Statistics.DataBytesSent);
                    Assert.AreEqual(0, connection.Statistics.DataBytesReceived);
                }
        }
        public void KeepAliveClientTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                    connection.KeepAliveInterval = 100;

                    Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                    Assert.IsTrue(
                        connection.Statistics.TotalBytesSent >= 30 &&
                        connection.Statistics.TotalBytesSent <= 50,
                        "Sent: " + connection.Statistics.TotalBytesSent
                        );
                }
        }
Beispiel #18
0
        public static async Task <QueryResults> QueryAsync(RSAAsymmetricKey key, Target target, TimeSpan timeout)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var tcs = new TaskCompletionSource <QueryResults>();

            var connection = new UdpClientConnection(GablarskiProtocol.Instance, key);

            connection.Start(MessageTypes.Unreliable);

            var cancelSources = new CancellationTokenSource(timeout);

            cancelSources.Token.Register(() => {
                tcs.TrySetCanceled();
                connection.Dispose();
            });

            connection.ConnectionlessMessageReceived += (sender, args) => {
                var results = args.Message as QueryServerResultMessage;
                if (results == null)
                {
                    return;
                }

                tcs.TrySetResult(new QueryResults(results.ServerInfo, results.Channels, results.Users));

                connection.Dispose();
            };

            await connection.SendConnectionlessMessageAsync(new QueryServerMessage(), target).ConfigureAwait(false);

            return(await tcs.Task.ConfigureAwait(false));
        }
Beispiel #19
0
        public IEnumerator CoConnect()
        {
            // Don't leak connections!
            if (this.connection != null)
            {
                yield break;
            }

            // Initialize streams (once)
            if (this.Streams == null)
            {
                this.Streams = new MessageWriter[2];
                for (int i = 0; i < this.Streams.Length; ++i)
                {
                    this.Streams[i] = MessageWriter.Get((SendOption)i);
                }
            }

            // Clear any existing data, and prep them for batching
            for (int i = 0; i < this.Streams.Length; ++i)
            {
                var stream = this.Streams[i];
                stream.Clear((SendOption)i);
                stream.StartMessage((byte)PlayerMessageTags.GameData);
                stream.Write(this.GameId);
            }

            this.connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, ServerPort));
            this.connection.DataReceived += HandleMessage;
            this.connection.Disconnected += HandleDisconnect;

            // If you block in a Unity Coroutine, it'll hang the game!
            this.connection.ConnectAsync(GetConnectionData());

            while (this.connection != null && this.connection.State != ConnectionState.Connected)
            {
                yield return(null);
            }
        }
        /// <summary>
        /// Initializes this client by connecting to the specified host and attempting
        /// to join the specified lobby code. Will throw if connection fails, else will
        /// start servicing messages in the background. The caller is responsible for
        /// ensuring that the application stays running as long as the client is active.
        /// </summary>
        public async Task Connect(IPAddress address, string lobbyName, ushort port = MATCHMAKER_PORT)
        {
            _address   = address;
            _lobbyName = lobbyName;
            _lobbyCode = GameCode.GameNameToIntV2(lobbyName);

            var(connection, response) = await ConnectToMMAndSend(address, port, JoinGame);

            _port = (ushort)connection.EndPoint.Port;

            _connection = connection;
            _connection.DataReceived += OnMessageReceived;
            _connection.Disconnected += (sender, args) => { OnDisconnect?.Invoke(); };

            HandleJoinGameResult(response);

            if (!_hasPlayerData)
            {
                // If we don't have user data, send a SceneChange so that we receive a spawn.
                _connection.SendReliableMessage(writer =>
                {
                    writer.StartMessage((byte)MMTags.GameData);
                    writer.Write(_lobbyCode);
                    writer.StartMessage((byte)GameDataTags.SceneChange);
                    writer.WritePacked(_clientId); // note: must be _clientId since localplayer is not set yet
                    writer.Write("OnlineGame");
                    writer.EndMessage();
                    writer.EndMessage();
                });
            }
            else
            {
                // We have user data, invoke listeners.
                _hasReconnectedAfterPlayerData = true;

                OnConnect?.Invoke();
                OnPlayerDataUpdate?.Invoke(_playerData);
            }
        }
        public void ServerExtraDataDisconnectTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    string           received = null;
                    ManualResetEvent mutex    = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        // We don't own the message, we have to read the string now
                        received = args.Message.ReadString();
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        // As it turns out, the UdpConnectionListener can have an issue on loopback where the disconnect can happen before the hello confirm
                        // Tossing it on a different thread makes this test more reliable. Perhaps something to think about elsewhere though.
                        Task.Run(async() =>
                        {
                            await Task.Delay(1);
                            MessageWriter writer = MessageWriter.Get(SendOption.None);
                            writer.Write("Goodbye");
                            args.Connection.Disconnect("Testing", writer);
                        });
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.IsNotNull(received);
                    Assert.AreEqual("Goodbye", received);
                }
        }
        public void UdpHandshakeTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    MessageReader output = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs e)
                    {
                        output = e.HandshakeData;
                    };

                    connection.Connect(TestData);

                    Thread.Sleep(10);
                    for (int i = 0; i < TestData.Length; ++i)
                    {
                        Assert.AreEqual(TestData[i], output.ReadByte());
                    }
                }
        }
        public void MixedConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener2 = new ThreadLimitedUdpConnectionListener(4, new IPEndPoint(IPAddress.IPv6Any, 4296), new ConsoleLogger(), IPMode.IPv6))
            {
                listener2.Start();

                listener2.NewConnection += (evt) =>
                {
                    Console.WriteLine($"Connection: {evt.Connection.EndPoint}");
                };

                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296)))
                {
                    connection.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                }

                using (UdpConnection connection2 = new UdpClientConnection(new IPEndPoint(IPAddress.IPv6Loopback, 4296), IPMode.IPv6))
                {
                    connection2.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection2.State);
                }
            }
        }
        public void MixedConnectionTest()
        {
            using (UdpConnectionListener listener2 = new UdpConnectionListener(new IPEndPoint(IPAddress.IPv6Any, 4296), IPMode.IPv6))
            {
                listener2.Start();

                listener2.NewConnection += (evt) =>
                {
                    Console.WriteLine("v6 connection: " + ((NetworkConnection)evt.Connection).GetIP4Address());
                };

                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296)))
                {
                    connection.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                }

                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.IPv6Loopback, 4296), IPMode.IPv6))
                {
                    connection.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                }
            }
        }
        public void ServerDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    ManualResetEvent mutex = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        args.Connection.Disconnect("Testing");
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();
                }
        }
Beispiel #26
0
        /// <summary>
        /// Connect to the specified ip:port endpoint for the matchmaker, then send the specified
        /// message. Returns a task that resolves to a tuple of the established connection and the
        /// first message received from the matchmaker in response to the sent message (usually
        /// the join/host confirmal message). Will throw if the connection closes prematurely or
        /// otherwise errors. Otherwise, the task itself is responsible for disposing of the
        /// connection once the server disconnects.
        /// </summary>
        private static async Task <(UdpClientConnection, MessageReader)> ConnectToMMAndSend(IPAddress address,
                                                                                            ushort port, Action <MessageWriter> writeMessage)
        {
            var firstMessageTask = new TaskCompletionSource <MessageReader>();

            var connection = new UdpClientConnection(new IPEndPoint(address, port));

            connection.KeepAliveInterval    = 1000;
            connection.DisconnectTimeout    = 10000;
            connection.ResendPingMultiplier = 1.2f;

            // Set up an event handler to resolve the task on first non-reselect message received.
            Action <DataReceivedEventArgs> onDataReceived = null;

            onDataReceived = args =>
            {
                try
                {
                    var msg = args.Message.ReadMessage();
                    if (msg.Tag == (byte)MMTags.ReselectServer)
                    {
                        return;                                          // not interested
                    }
                    firstMessageTask.TrySetResult(msg);
                    connection.DataReceived -= onDataReceived;
                }
                finally
                {
                    args.Message.Recycle();
                }
            };
            connection.DataReceived += onDataReceived;

            // Set up an event handler to set an exception for the task on early disconnect.
            connection.Disconnected += (sender, args) =>
            {
                connection.Dispose();
                firstMessageTask.TrySetException(new AUException("Connection to matchmaker prematurely exited"));
            };

            // Connect to the endpoint.
            connection.ConnectAsync(HANDSHAKE);
            await connection.ConnectWaitLock.AsTask();

            // Send the contents.
            connection.SendReliableMessage(writeMessage);

            // Wait for the response to arrive.
            var response = await firstMessageTask.Task;

            // If this is not a redirect, return the result.
            if (response.Tag != (byte)MMTags.Redirect)
            {
                return(connection, response);
            }

            // This is a redirect, so do this again but with the new data.
            var newIp   = response.ReadUInt32();
            var newPort = response.ReadUInt16();

            // Reconnect to new host.
            return(await ConnectToMMAndSend(new IPAddress(newIp), newPort, writeMessage));
        }