Exemplo n.º 1
0
    public void ReceivePositionInformation(int hostId, int connectionId, PositionMessage message)
    {
        if (!GameStarted())
        {
            return;
        }

        int    lane   = System.Convert.ToInt32(message.lane);
        Player player = players.FirstOrDefault(p => p.lane != null && p.lane.id == lane);

        if (player != null)
        {
            player.transform.position = message.position;
            player.SetHealth(System.Convert.ToInt32(message.hp));
        }
        else
        {
            SpawnPlayer(lane);
        }

        P2PConnection connection = P2PConnectionManager.GetConnection(hostId, connectionId);

        if (connection != null)
        {
            connection.lane = lane;
        }
    }
Exemplo n.º 2
0
        private async void button5_Click(object sender, RoutedEventArgs e)
        {
            List <PeerAddress> ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.DNSSeedHosts, _networkParameters);

            Thread threadLable = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Dispatcher.Invoke(() =>
                    {
                        label.Content = "Inbound: " + P2PConnectionManager.GetInboundP2PConnections().Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
                    });
                    Thread.CurrentThread.Join(1000);
                }
            }));

            threadLable.IsBackground = true;
            threadLable.Start();

            foreach (PeerAddress ip in ips)
            {
                Thread connectThread = new Thread(new ThreadStart(() =>
                {
                    P2PConnection p2p = new P2PConnection(ip.IPAddress, _networkParameters, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
                    p2p.ConnectToPeer(1);
                }));
                connectThread.IsBackground = true;
                connectThread.Start();
            }
        }
Exemplo n.º 3
0
        private async void button1_Click(object sender, RoutedEventArgs e)
        {
            Thread threadLable = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Dispatcher.Invoke(() =>
                    {
                        List <P2PConnection> inNodes = P2PConnectionManager.GetInboundP2PConnections();
                        label.Content = "Inbound: " + inNodes.Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;

                        if (inNodes.Count > 0)
                        {
                        }
                    });

                    Thread.CurrentThread.Join(1000);
                }
            }));

            threadLable.IsBackground = true;
            threadLable.Start();

            await P2PConnectionManager.ListenForIncomingP2PConnectionsAsync(IPAddress.Any, _networkParameters);
        }
Exemplo n.º 4
0
    static void CreateNetworkReader(byte[] data)
    {
        //https://docs.unity3d.com/ScriptReference/Networking.NetworkReader.html
        NetworkReader networkReader = new NetworkReader(data);

        // The first two bytes in the buffer represent the size of the message. This is equal to the NetworkReader.Length
        // minus the size of the prefix.
        networkReader.ReadBytes(2);
        //short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]);

        // The message type added in NetworkWriter.StartMessage is to be read now. It is a short and so consists of
        // two bytes. It is the second two bytes on the buffer.
        byte[] readerMsgTypeData = networkReader.ReadBytes(2);
        short  readerMsgType     = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]);

        //Debug.Log("Message of type " + readerMsgType + " received");

        if (readerMsgType == MessageTypes.JoinRequest)
        {
            JoinRequestMessage message = new JoinRequestMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinRequest(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnswer)
        {
            JoinAnswerMessage message = new JoinAnswerMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnswer(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.JoinAnnounce)
        {
            JoinAnnounceMessage message = new JoinAnnounceMessage();
            message.Deserialize(networkReader);
            P2PConnectionManager.OnJoinAnnounce(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.Position)
        {
            PositionMessage message = new PositionMessage();
            message.Deserialize(networkReader);
            p2PController.ReceivePositionInformation(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AskConsent)
        {
            AskConsentMessage message = new AskConsentMessage();
            message.Deserialize(networkReader);
            p2PController.OnAskForConsentMsg(recHostId, connectionId, message);
        }
        else if (readerMsgType == MessageTypes.AnswerConsent)
        {
            AnswerConsentMessage message = new AnswerConsentMessage();
            message.Deserialize(networkReader);
            P2PConsentManager.ReceiveAnswerConsent(message);
        }
        else if (readerMsgType == MessageTypes.ApplyConsent)
        {
            ApplyConsentMessage message = new ApplyConsentMessage();
            message.Deserialize(networkReader);
            p2PController.ApplyConsent(message);
        }
    }
Exemplo n.º 5
0
    public static void OnJoinAnnounce(int hostId, int connectionId, JoinAnnounceMessage message)
    {
        Debug.Log("OnJoinAnnounce received");
        P2PConnection connection = P2PConnectionManager.GetConnection(hostId, connectionId);

        connection.SuccessfullyConnect();
    }
Exemplo n.º 6
0
 /// <summary>
 /// Special case constructor, used for the genesis node, cloneAsHeader and unit tests.
 /// </summary>
 internal BlockMessage(P2PNetworkParameters netParams) : base(netParams)
 {
     // Set up a few basic things. We are not complete after this though.
     _version          = 1;
     _difficultyTarget = 0x1d07fff8;
     _time             = (uint)P2PConnectionManager.GetUTCNowWithOffset();
     _prevBlockHash    = new byte[32];
 }
Exemplo n.º 7
0
 /// <summary>
 /// Construct a peer address from a memorized or hardcoded address.
 /// </summary>
 public PeerAddress(IPAddress addr, ushort port, ulong services, P2PNetworkParameters netParams, bool isInVersionMessage = false) : base(netParams)
 {
     _addr               = addr;
     _port               = port;
     _time               = (uint)P2PConnectionManager.GetUTCNowWithOffset();
     ProtocolVersion     = netParams.ClientVersion;
     _services           = services;
     _isInVersionMessage = isInVersionMessage;
 }
Exemplo n.º 8
0
 public VersionMessage(IPAddress remoteIpAddress, ushort remotePort, Socket sock, uint newBestHeight, uint remoteClientVersion, P2PNetworkParameters netParams, ulong remoteServices = (ulong)P2PNetworkParameters.NODE_NETWORK.FULL_NODE) : base(netParams)
 {
     _localServices    = P2PNetParameters.Services;
     _time             = P2PConnectionManager.GetUTCNowWithOffset();
     _myAddr           = new PeerAddress(IPAddress.Loopback, Convert.ToUInt16(((IPEndPoint)sock.LocalEndPoint).Port), netParams.Services, P2PNetParameters, true);
     _theirAddr        = new PeerAddress(remoteIpAddress, remotePort, remoteServices, P2PNetParameters, true);
     _nonce            = P2PNetworkParameters.VersionConnectNonce;
     _userAgent        = P2PNetworkParameters.UserAgentString;
     _startBlockHeight = newBestHeight;
     _relay            = P2PNetParameters.Relay;
 }
Exemplo n.º 9
0
        public async void StarteMe()
        {
            P2PNetworkParameters netParams = new P2PNetworkParameters(P2PNetworkParameters.ProtocolVersion, false, 20966, (ulong)P2PNetworkParameters.NODE_NETWORK.FULL_NODE, (int)P2PNetworkParameters.RELAY.RELAY_ALWAYS);

            //start threaded loop listening for peers
            if (netParams.ListenForPeers)
            {
                await P2PConnectionManager.ListenForIncomingP2PConnectionsAsync(IPAddress.Any, netParams);
            }

            //start threaded loop maintaining max outbound connections to peers
            P2PConnectionManager.MaintainConnectionsOutbound(netParams);
        }
Exemplo n.º 10
0
    public static void ConnectEvent(int hostId, int connectionId)
    {
        int    port;
        string ip;

        UnityEngine.Networking.Types.NetworkID netId;
        UnityEngine.Networking.Types.NodeID    nodeId;
        NetworkTransport.GetConnectionInfo(hostId, connectionId, out ip, out port, out netId, out nodeId, out P2PController.error);

        P2PConnection connection = P2PConnectionManager.GetConnection(ip, port);

        if (connection == null)
        {
            //new connection from targeted ip or new player
            connection      = new P2PConnection(hostId, connectionId);
            connection.ip   = ip;
            connection.port = port;
            connections.Add(connection);
            Debug.Log("New connection with " + connection);

            if (!JoinRequestSend)            //I'm wanting to join
            {
                Debug.Log("Sending Join Request");
                JoinRequestSend = true;
                JoinRequestMessage message = new JoinRequestMessage();
                P2PSender.Send(hostId, connectionId, P2PChannels.ReliableChannelId, message, MessageTypes.JoinRequest);
            }
            else if (JoinAnswerReceived && !p2PController.GameStarted())
            {
                connection.SuccessfullyConnect();
            }
        }
        else if (!connection.ConnectionSuccessful())
        {
            //successfully connect to an existing player. Connection requested previously
            connection.hostId       = hostId;
            connection.connectionId = connectionId;
            connection.SuccessfullyConnect();

            JoinAnnounceMessage announceMessage = new JoinAnnounceMessage();
            P2PSender.Send(hostId, connectionId, P2PChannels.ReliableChannelId, announceMessage, MessageTypes.JoinAnnounce);
        }

        if (!p2PController.GameStarted())
        {
            if (JoinAnswerReceived)
            {
                CheckConnectionsStatus();
            }
        }
    }
Exemplo n.º 11
0
        private async void button4_Click(object sender, RoutedEventArgs e)
        {
            List <PeerAddress> ips;

            if (!_networkParameters.IsTestNet)
            {
                ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.DNSSeedHosts, _networkParameters);
            }
            else
            {
                ips = await P2PConnectionManager.GetDNSSeedIPAddressesAsync(P2PNetworkParameters.TestNetDNSSeedHosts, _networkParameters);
            }
            MessageBox.Show(ips.Count.ToString());
        }
Exemplo n.º 12
0
        private bool pCheckTimestamp()
        {
            var currentTime = P2PConnectionManager.GetUTCNowWithOffset();

            if (_time > currentTime + _allowedTimeDrift)
            {
#if (DEBUG)
                Console.WriteLine("Block too far in future");
#endif
                return(false);
            }

            return(true);
        }
Exemplo n.º 13
0
    public static void Listen()
    {
        byte[]           recBuffer  = new byte[P2PController.bufferLength];
        int              bufferSize = P2PController.bufferLength;
        int              dataSize;
        byte             error;
        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

        while (recData != NetworkEventType.Nothing)
        {
            if (Recorder.session != null)
            {
                Recorder.session.messagesReceived++;
                Recorder.session.AddIncomingBandwidth(dataSize);
                if (channelId == P2PChannels.ReliableChannelId)
                {
                    Recorder.session.importantMessagesReceived++;
                }
            }
            //Debug.Log("Adding data size: " + dataSize);

            //Debug.Log("Received: " + recData + ", recHostId: " + recHostId + ", connectionId: " + connectionId +
            //			", channelId: " + channelId + ", recBuffer: " + Encoding.UTF8.GetString(recBuffer));
            channelId++;              //get rid of warning

            switch (recData)
            {
            case NetworkEventType.Nothing:
                break;

            case NetworkEventType.ConnectEvent:
                P2PConnectionManager.ConnectEvent(recHostId, connectionId);
                break;

            case NetworkEventType.DataEvent:
                CreateNetworkReader(recBuffer);
                break;

            case NetworkEventType.DisconnectEvent:
                P2PConnectionManager.RemoveConnection(recHostId, connectionId);
                break;

            case NetworkEventType.BroadcastEvent:
                break;
            }

            recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
        }
    }
Exemplo n.º 14
0
    public static void RemoveConnection(int hostId, int connectionId)
    {
        P2PConnection connection = P2PConnectionManager.GetConnection(hostId, connectionId);

        if (connection == null)
        {
            Debug.Log("Warning! Connection with " + connection + " doesn't exist");
        }
        else
        {
            p2PController.DespawnPlayer(connection.lane);
            connections.Remove(connection);
            Debug.Log("Remove connection with " + connection);
        }
    }
Exemplo n.º 15
0
    public void AskForConsent(ConsentMessage consentMessage)
    {
        AskConsentMessage message = new AskConsentMessage();

        message.consentId     = P2PConsentManager.GetNextConsentIdAndIncrement();
        message.consentAction = consentMessage.consentAction;
        message.result        = consentMessage.result;
        message.parameters.AddRange(consentMessage.parameters);
        if (consensusAlgorithm && P2PConnectionManager.SuccessfulConnectionsCount() > 0)
        {
            Debug.Log("P2P: Asking consent for: " + consentMessage.consentAction);
            P2PConsentManager.AddPendingConsent(message);
            P2PSender.SendToAll(P2PChannels.ReliableChannelId, message, MessageTypes.AskConsent);
        }
        else
        {
            Debug.Log("P2P: Imposing consent for: " + consentMessage.consentAction);
            P2PConsentManager.ApplyAndSpreadConsentResult(OnAskForConsentMsg(-1, -1, message));
        }
    }
Exemplo n.º 16
0
    public void LeaveGame()
    {
        initialized = false;
        P2PConnectionManager.DisconnectAll();
        NetworkTransport.Shutdown();

        P2PConnectionManager.Reset();
        players.Clear();

        //destroy rockets and players
        Rocket[] rockets = FindObjectsOfType <Rocket>();
        foreach (Rocket rocket in rockets)
        {
            Destroy(rocket.gameObject);
        }

        Player[] ps = FindObjectsOfType <Player>();
        foreach (Player p in ps)
        {
            Destroy(p.gameObject);
        }
    }
Exemplo n.º 17
0
    public void ApplyConsent(ConsentMessage message)
    {
        Debug.Log("P2P: Applying consent for: " + message.consentAction);
        if (message.consentAction == ConsentAction.SpawnRocket)
        {
            bool cheating = !gameController.lanes[message.parameters[1]].spawnManager.ValidIndex(message.result);
            if (!cheating)
            {
                gameController.lanes[message.parameters[1]].spawnManager.Spawn(message.result);
            }
            else
            {
                Debug.Log("Cheat!");
                if (Recorder.session != null)
                {
                    Recorder.session.cheatsPassed++;
                }
            }
        }
        else if (message.consentAction == ConsentAction.JoinGame)
        {
            P2PConnection connection = P2PConnectionManager.GetConnection(message.parameters[0], message.parameters[1]);
            if (connection != null)
            {
                JoinAnswerMessage answerMessage = new JoinAnswerMessage();
                answerMessage.lane = message.result;
                answerMessage.successfulConnections = P2PConnectionManager.GetSuccessfulConnections();
                answerMessage.r = Convert.ToInt32(gameColor.r * 255);
                answerMessage.g = Convert.ToInt32(gameColor.g * 255);
                answerMessage.b = Convert.ToInt32(gameColor.b * 255);

                P2PSender.Send(message.parameters[0], message.parameters[1], P2PChannels.ReliableChannelId, answerMessage, MessageTypes.JoinAnswer);

                connection.SuccessfullyConnect();

                Debug.Log("Sending JoinAnswer with lane: " + answerMessage.lane + "and " + answerMessage.successfulConnections.Count + " connections");
            }
        }
    }
Exemplo n.º 18
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Thread connectThread = new Thread(new ThreadStart(() =>
            {
                ushort port = 8333;

                if (_networkParameters.IsTestNet)
                {
                    port = 18333;
                }

                p2p          = new P2PConnection(IPAddress.Parse("82.45.214.119"), _networkParameters, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp), port);
                bool success = p2p.ConnectToPeer(1);

                if (!success)
                {
                    MessageBox.Show("Not connected");
                }
            }));

            connectThread.IsBackground = true;
            connectThread.Start();

            Thread threadLable = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Dispatcher.Invoke(() =>
                    {
                        label.Content = "Inbound: " + P2PConnectionManager.GetInboundP2PConnections().Count + " Outbound: " + P2PConnectionManager.GetOutboundP2PConnections().Count;
                    });
                    Thread.CurrentThread.Join(250);
                }
            }));

            threadLable.IsBackground = true;
            threadLable.Start();
        }
Exemplo n.º 19
0
    public static void OnJoinAnswer(int hostId, int connectionId, JoinAnswerMessage message)
    {
        if (p2PController.GameStarted() || JoinAnswerReceived)
        {
            return;
        }

        Debug.Log("JoinAnswer received, lane: " + message.lane + ", playersCount: " + message.successfulConnections.Count);
        if (!(message.lane >= 0 && message.lane < 4))
        {
            Debug.Log("Game is full");
            p2PController.myLane = -1;
            p2PController.DisplayError("Game is full");
            return;
        }
        else
        {
            Debug.Log("allowed to join the game! Now need to connect to all players");
            JoinAnswerReceived = true;

            p2PController.myLane = message.lane;

            P2PController.gameColor = new Color(message.r / 255.0f, message.g / 255.0f, message.b / 255.0f);
            GameObject.FindObjectOfType <UIController>().UpdateGameColor(P2PController.gameColor);

            foreach (P2PConnection connection in message.successfulConnections)
            {
                connections.Add(connection);
                NetworkTransport.Connect(myHostId, connection.ip, connection.port, 0, out P2PController.error);
                P2PController.CheckError("Connect");
            }

            P2PConnectionManager.GetConnection(hostId, connectionId).SuccessfullyConnect();

            CheckConnectionsStatus();
        }
    }
Exemplo n.º 20
0
        protected override void Parse()
        {
            // Format of a serialized address:
            //   uint32 timestamp
            //   uint64 services   (flags determining what the node can do)
            //   16 bytes IP address
            //   2 bytes port num
            if (!_isInVersionMessage)
            {
                if (ProtocolVersion > 31402)
                {
                    _time = ReadUint32();
                }
                else
                {
                    _time = uint.MaxValue;
                }
            }
            else
            {
                _time = (uint)P2PConnectionManager.GetUTCNowWithOffset();
            }
            _services = ReadUint64();
            var addrBytes = ReadBytes(16);

            if (new BigInteger(addrBytes, 0, 12).Equals(BigInteger.ValueOf(0xFFFF)))
            {
                var newBytes = new byte[4];
                Array.Copy(addrBytes, 12, newBytes, 0, 4);
                addrBytes = newBytes;
            }
            _addr = new IPAddress(addrBytes);
            _port = Convert.ToUInt16((Bytes[Cursor++] << 8) | Bytes[Cursor++]);

            Bytes = null;
        }
Exemplo n.º 21
0
 public ParallelSocket(P2PConnectionManager manager, Stream ustr, int connectionID)
     : base(manager)
 {
     _underlyingstream = ustr;
     _manager = manager;
     _id = connectionID;
 }
Exemplo n.º 22
0
 private void button2_Click(object sender, RoutedEventArgs e)
 {
     P2PConnectionManager.StopListeningForIncomingP2PConnections();
 }
Exemplo n.º 23
0
 private async void button8_Click(object sender, RoutedEventArgs e)
 {
     await P2PConnectionManager.SetNATPortForwardingUPnPAsync(_networkParameters.P2PListeningPort, _networkParameters.P2PListeningPort);
 }