public override void StartClient(IPAddress ipAddress, int port)
 {
     udpConnection = new UdpClientConnection(ipAddress, port, this);
     IsServer      = false;
     Port          = port;
     IPAddress     = ipAddress;
 }
Пример #2
0
            private static IEnumerator Coroutine(UdpConnection connection)
            {
                yield return(new WaitForSeconds(3));

                var client = AmongUsClient.Instance;

                if (client != null && client.connection != null && client.connection.Equals(connection) && client.connection.State == ConnectionState.Connecting)
                {
                    var reactorPlugin = PluginSingleton <ReactorPlugin> .Instance;

                    if (reactorPlugin.AllowVanillaServers.Value)
                    {
                        if (reactorPlugin.CustomRpcManager.List.Any())
                        {
                            Logger <ReactorPlugin> .Warning("Config option AllowVanillaServers was set to true, but there are custom rpcs registered!");
                        }
                        else
                        {
                            connection.State = ConnectionState.Connected;
                            yield break;
                        }
                    }

                    client.LastDisconnectReason = DisconnectReasons.Custom;
                    client.LastCustomDisconnect = "Server didn't respond to modded handshake";
                    client.HandleDisconnect(client.LastDisconnectReason, client.LastCustomDisconnect);
                }
            }
        protected override Task <IObservable <LocalisationData> > InitializeCore()
        {
            return(Task.Run(
                       () =>
            {
                IObservable <byte[]> packets;

                switch (this.ConnectionType)
                {
                case ConnectionType.Serial:
                    packets = ToNcomPacket(SerialConnection.CreateByteListener(this.SerialPortName, this.SerialBaudRate, Parity.None, 8, StopBits.One));
                    break;

                case ConnectionType.Udp:
                    packets = UdpConnection.CreateListener(this.RemoteAddress, this.UdpListenerPort).Select(udpResult => udpResult.Buffer);
                    break;

                default:
                    throw new NotSupportedException(string.Format("Connection type '{0}' is not supported.", this.ConnectionType));
                }

                return (
                    from geoData in ToGeoData(packets)
                    select new LocalisationData {
                    RawData = geoData,
                    GpsStatus = (IsInitializing(geoData) ? GpsStatus.Initializing : geoData.PositionData.Longitude == 0 && geoData.PositionData.Latitude == 0 ? GpsStatus.SignalLost : GpsStatus.Reliable)
                }).Publish().RefCount();
            }));
        }
    void Start()
    {
        QualitySettings.vSyncCount  = 0;
        Application.targetFrameRate = 100;

        // the ChartGraph info is obtained via the inspector
        if (chart == null)
        {
            return;
        }

        // calling StartBatch allows changing the graph data without redrawing the graph for every change
        chart.DataSource.StartBatch();
        chart.DataSource.ClearCategory("Player 1");
        chart.DataSource.ClearCategory("Player 2");

        chart.DataSource.AddPointToCategory("Player 1", 0, 0);
        chart.DataSource.AddPointToCategory("Player 2", x, Receive_level_Tank_1);


        // finally we call EndBatch , this will cause the GraphChart to redraw itself
        chart.DataSource.EndBatch();

        startPosition = Meter_Gauge.transform.position;
        connection    = new UdpConnection();
        connection.StartConnection(sendIp, sendPort, receivePort);
    }
Пример #5
0
        public ActiveSearch()
        {
            UpdateBase = new FmdcEventHandler(ActiveSearch_UpdateBase);

            HubSetting settings = new HubSetting();

            settings.Address     = "127.0.0.1";
            settings.Port        = 411;
            settings.DisplayName = "FlowLib";
            settings.Protocol    = "Auto";

            hubConnection = new Hub(settings, this);
            hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange);
            hubConnection.Connect();

            Share share = new Share("Test");

            share.Port = 1000;

            // Telling that we are listening on port 1000 for incomming search results (Any means from everyone)
            UdpConnection udp = new UdpConnection(new IPEndPoint(IPAddress.Any, share.Port));

            udp.Protocol = new FlowLib.Protocols.UdpNmdcProtocol();
            udp.Protocol.MessageReceived += new FmdcEventHandler(Protocol_MessageReceived);
            // Enable Active searching
            hubConnection.Me.Mode = FlowLib.Enums.ConnectionTypes.Direct;
            hubConnection.Share   = share;
        }
Пример #6
0
        public ConnectionViewModel(ILogger logger)
        {
            DisplayName = "Connection";
            Connections = new List <IConnection>();
            _serial     = new SerialConnection();
            if (_serial.AvailablePorts.Any(x => x.Equals(Settings.Default.SerialPort, StringComparison.InvariantCultureIgnoreCase)))
            {
                _serial.Portname = Settings.Default.SerialPort;
            }
            _serial.Baudrate = Settings.Default.Baudrate;

            Connections.Add(_serial);
            _udp            = new UdpConnection(logger);
            _udp.TerminalIp = Settings.Default.TerminalIp;
            _udp.Port       = Settings.Default.NetworkPort;
            Connections.Add(_udp);

            if (Settings.Default.UseSerialPort)
            {
                IsSerialConnection = true;
            }
            else
            {
                IsNetworkConnection = true;
            }
        }
Пример #7
0
        protected async Task Receive(Action <byte[]> callbackForReceiveData = null)
        {
            var udpResult = await UdpConnection.ReceiveAsync();

            byte[] receivedData = udpResult.Buffer;
            callbackForReceiveData(receivedData);
        }
Пример #8
0
 public PlayerConnection(
     ILogger logger,
     UdpConnection connection,
     INetworkPacketController packetHandler)
     : base(logger, connection, packetHandler)
 {
 }
Пример #9
0
            public static void Prefix(UdpConnection __instance, byte sendOption, ref Il2CppSystem.Action ackCallback)
            {
                if (sendOption != 8 || AmongUsClient.Instance == null || AmongUsClient.Instance.connection == null || !AmongUsClient.Instance.connection.Equals(__instance))
                {
                    return;
                }

                if (!PluginSingleton <ReactorPlugin> .Instance.ModdedHandshake.Value)
                {
                    return;
                }

                ackCallback = (System.Action)(() =>
                {
                    if (__instance.State != ConnectionState.Connected)
                    {
                        PluginSingleton <ReactorPlugin> .Instance.Log.LogDebug("Hello was acked, waiting for modded handshake response");

                        Coroutines.Start(Coroutine());

                        __instance.add_Disconnected((Action <Il2CppSystem.Object, DisconnectedEventArgs>)((a, b) =>
                        {
                            Coroutines.Stop(Coroutine());
                        }));
                    }
                });
            }
        public void ClientDisposeDisconnectTest()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);

            bool serverConnected    = false;
            bool serverDisconnected = false;
            bool clientDisconnected = false;

            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(ep, new TestLogger()))
                {
                    listener.NewConnection += (evt) =>
                    {
                        serverConnected              = true;
                        evt.Connection.Disconnected += (o, et) => serverDisconnected = true;
                    };

                    connection.Disconnected += (o, et) => clientDisconnected = true;

                    listener.Start();
                    connection.Connect();

                    Thread.Sleep(100); // Gotta wait for the server to set up the events.
                    connection.Dispose();

                    Thread.Sleep(100);

                    Assert.IsTrue(serverConnected);
                    Assert.IsTrue(serverDisconnected);
                    Assert.IsFalse(clientDisconnected);
                }
        }
Пример #11
0
        static void EventLoop(UdpSocket socket)
        {
            UdpConnection c = null;

            while (true)
            {
                UdpEvent ev = default(UdpEvent);

                if (socket.Poll(ref ev))
                {
                    UdpLog.User(ev.EventType.ToString());

                    switch (ev.EventType)
                    {
                    case UdpEventType.ConnectRequest:
                        socket.Accept(ev.EndPoint);
                        break;

                    case UdpEventType.Connected:
                        c = ev.Connection;
                        break;
                    }
                }

                if (c != null)
                {
                    c.Send(10u);
                }

                Thread.Sleep(100);
            }
        }
        public void ClientDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    ManualResetEvent mutex  = new ManualResetEvent(false);
                    ManualResetEvent mutex2 = new ManualResetEvent(false);

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        args.Connection.Disconnected += delegate(object sender2, DisconnectedEventArgs args2)
                        {
                            mutex2.Set();
                        };

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne(1000);
                    Assert.AreEqual(ConnectionState.Connected, connection.State);

                    connection.Disconnect("Testing");

                    mutex2.WaitOne(1000);
                    Assert.AreEqual(ConnectionState.NotConnected, connection.State);
                }
        }
        public void ServerExtraDataDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    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)
                    {
                        MessageWriter writer = MessageWriter.Get(SendOption.None);
                        writer.Write("Goodbye");
                        args.Connection.Disconnect("Testing", writer);
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne(5000);

                    Assert.IsNotNull(received);
                    Assert.AreEqual("Goodbye", received);
                }
        }
        public void UdpUnreliableMessageSendTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    MessageReader output = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs e)
                    {
                        e.Connection.DataReceived += delegate(DataReceivedEventArgs evt)
                        {
                            output = evt.Message.Duplicate();
                        };
                    };

                    listener.Start();
                    connection.Connect();

                    for (int i = 0; i < 4; ++i)
                    {
                        var msg = MessageWriter.Get(SendOption.None);
                        msg.Write(TestData);
                        connection.Send(msg);
                        msg.Recycle();
                    }

                    Thread.Sleep(10);
                    for (int i = 0; i < TestData.Length; ++i)
                    {
                        Assert.AreEqual(TestData[i], output.ReadByte());
                    }
                }
        }
Пример #15
0
 protected override RavenNetworkConnection CreateConnection(
     ILogger logger,
     UdpConnection connection,
     INetworkPacketController packetController)
 {
     return(new PlayerConnection(logger, connection, packetController));
 }
Пример #16
0
            public static void Prefix(UdpConnection __instance, byte sendOption, ref Il2CppSystem.Action ackCallback)
            {
                if (sendOption != 8 || AmongUsClient.Instance == null || AmongUsClient.Instance.connection == null || !AmongUsClient.Instance.connection.Equals(__instance))
                {
                    return;
                }

                ackCallback = (Action)(() =>
                {
                    if (__instance.State == ConnectionState.Connected)
                    {
                        return;
                    }

                    Logger <ReactorPlugin> .Debug("Hello was acked, waiting for modded handshake response");

                    var coroutine = Coroutines.Start(Coroutine(__instance));

                    __instance.Disconnected = Il2CppSystem.Delegate.Combine(
                        (Il2CppSystem.EventHandler <DisconnectedEventArgs>)(Action <Il2CppSystem.Object, DisconnectedEventArgs>) ((_, _) =>
                    {
                        Coroutines.Stop(coroutine);
                    }),
                        __instance.Disconnected
                        ).Cast <Il2CppSystem.EventHandler <DisconnectedEventArgs> >();
                });
            }
Пример #17
0
        public override void Disconnect()
        {
            LoggerManager.Instance.Debug("Logic call Disconnect");

            object obj = statusLock;

            Monitor.Enter(obj);
            try
            {
                connectionStatus = ConnectionStatus.ClosedByLogic;
            }
            finally
            {
                Monitor.Exit(obj);
            }

            if (connection != null)
            {
                connection.Disconnect(null);
                connection = null;
            }

            if (socket != null)
            {
                socket.Close();
            }
        }
Пример #18
0
        public void KeepAliveServerTest()
        {
            ManualResetEvent mutex = new ManualResetEvent(false);

            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    UdpConnection client = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        client = (UdpConnection)args.Connection;
                        client.KeepAliveInterval = 100;

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

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.AreEqual(ConnectionState.Connected, client.State);

                    Assert.IsTrue(
                        client.Statistics.TotalBytesSent >= 27 &&
                        client.Statistics.TotalBytesSent <= 50,
                        "Sent: " + client.Statistics.TotalBytesSent
                        );
                }
        }
Пример #19
0
        void ProcessUdpDisConnection(UdpConnection udpCon)
        {
            string address = udpCon.RemoteEndPoint.Address.ToString();
            int    port    = udpCon.RemoteEndPoint.Port;

            //host <--> server connection
            if (hostUser.IsProxyServer(address, port) == true)
            {
                Debug.LogError("ProcessUdpDisConnection#ProxyServer ipv4:" + udpCon.RemoteEndPoint.ToString());
                hostUser.PeerConnect = null;

                //通知外部事件更改.
                NetWorkStateInfo info = new NetWorkStateInfo();
                info.state = EClientNetWorkState.DisConnected;
                owner.CallUdpProxyServerState(info);
                return;
            }

            /*
             * foreach (KeyValuePair<UInt32, P2PUser> peerUser in peerList)
             * {
             *      if (peerUser.Value.PeerConnect == null)
             *      {
             *              Log.info("P2PClientNetWork",  "ProcessUdpDisConnection#ignore uin:" + peerUser.Key);
             *              continue;
             *      }
             *
             *      if ( peerUser.Value.IsUserPoint(address, port) == true )
             *      {
             *              Log.info("P2PClientNetWork",  "ProcessUdpDisConnection#Find user:"******" ipv4:" + udpCon.RemoteEndPoint.ToString());
             *              peerUser.Value.PeerConnect = null;
             *              return;
             *      }
             * }*/
        }
        public void KeepAliveServerTest()
        {
            ManualResetEvent mutex = new ManualResetEvent(false);
            UdpConnection    listenerConnectionToClient = null;

            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.NewConnection += delegate(object sender, NewConnectionEventArgs args)
                    {
                        listenerConnectionToClient = (UdpConnection)args.Connection;
                        listenerConnectionToClient.KeepAliveInterval = 100;

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

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.IsNotNull(listenerConnectionToClient);
                    Assert.IsTrue(
                        listenerConnectionToClient.Statistics.TotalBytesSent >= 30 &&
                        listenerConnectionToClient.Statistics.TotalBytesSent <= 50,
                        "Sent: " + listenerConnectionToClient.Statistics.TotalBytesSent
                        );
                }
        }
Пример #21
0
 // Use this for initialization
 void Start()
 {
     _udp = new UdpConnection();
     _udp.ReceiveEvent += OnReceive;
     Connect();
     Send();
 }
 public void StartServer(int port)
 {
     isServer   = true;
     this.port  = port;
     connection = new UdpConnection(port, this);
     enabled    = true;
 }
Пример #23
0
        protected override TransportMessage NewTransport(string uri, Resources resources)
        {
            UdpListener udpListener = resources.Get(UDP_LISTENER) as UdpListener;
            IPEndPoint  ipEndPoint  = resources.Get(SOCKET_ADDRESS) as IPEndPoint;

            URL             url             = new URL(uri);
            TransportPacket transportPacket = null;

            if (udpListener != null)
            {
                transportPacket = new UdpConnection(ipEndPoint, udpListener);
            }
            else
            {
                transportPacket = new UdpConnection(url);
            }

            TransportMessage transportMessage = new Messagizer(transportPacket, url, resources);

            transportMessage = AddFilters(transportMessage, url, resources);

            ValueFactory vf = (ValueFactory)resources.Get(TransportConsts.VALUE_FACTORY);

            vf.LockDynamicTypes();

            return(transportMessage);
        }
 public void UdpReliableClientToServerTest()
 {
     using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
         using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
         {
             TestHelper.RunClientToServerTest(listener, connection, 10, SendOption.Reliable);
         }
 }
Пример #25
0
 internal ConnectionOpenedEventArgs(UdpConnection connection)
 {
     if (connection == null)
     {
         throw new ArgumentNullException(nameof(connection));
     }
     this.Connection = connection;
 }
Пример #26
0
        public RavenNetworkConnection Get(MessageReader handshakeData, UdpConnection connection)
        {
            var gameConnection = CreateConnection(logger, connection, packetHandlers);

            gameConnection.Disconnected += Connection_Disconnected;
            lock (mutex) connections.Add(gameConnection);
            return(gameConnection);
        }
Пример #27
0
        private void test_Click(object sender, RoutedEventArgs e)
        {
            udp            = new UdpConnection();
            udp.OnReceive += Udp_OnReceive;

            //udp.Start();
            //udp.Send(new byte[] { 1,2,3});
        }
Пример #28
0
    // Use this for initialization
    private PacketProcessor()
    {
        string serverIp    = "10.17.65.68";
        int    sendPort    = 11000;
        int    receivePort = 11000;

        _connection = new UdpConnection();
        _connection.StartConnection(serverIp, sendPort, receivePort);
    }
Пример #29
0
        void Start()
        {
            udp = new UdpConnection();
            udp.Connect("", 7777);

            udp.ReceiveEvent += OnReceive;

            udp.DisConnect();
        }
Пример #30
0
    void Start()
    {
        string sendIp      = "192.168.2.254";
        int    sendPort    = 11000;
        int    receivePort = 8881;

        connection = new UdpConnection();
        connection.StartConnection(sendIp, sendPort, receivePort);
    }
Пример #31
0
			protected override bool TryGetConnection (int connectionId, out UdpConnection oconnection)
			{
				oconnection = null;
				if (this.connection.ConnectionId == 0 || connectionId == this.connection.ConnectionId)
				{
					oconnection = this.connection;
					return true;
				}

				return false;
			}
Пример #32
0
        protected override bool TryGetConnection(int connectionId, out UdpConnection connection)
        {
            connection = null;

            UdpServerConnection server;
            bool found = this.connections.TryGetValue (connectionId, out server);
            if (found)
            {
                connection = server;
                return true;
            }

            return false;
        }
Пример #33
0
		protected abstract bool TryGetConnection (int connectionId, out UdpConnection connection);
Пример #34
0
 static void connectionStats(UdpConnection c)
 {
     UdpConnectionStats s = c.Stats;
     Console.WriteLine("{0}: {1} / {2} / {3} / {4}", c.RemoteEndPoint, s.PacketsSent, s.PacketsReceived, s.CommandSent, s.CommandsReceived);
 }