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
    public virtual void Initialize(P2PPeer peer, int networkConnectionId, HostTopology hostTopology)
    {
        this.m_Writer       = new P2PNetworkWriter();
        this.m_Reader       = new P2PNetworkReader();
        this.m_ConnectionId = networkConnectionId;
        this.m_Peer         = peer;
        int channelCount = hostTopology.DefaultConfig.ChannelCount;
        int packetSize   = (int)hostTopology.DefaultConfig.PacketSize;

        if (hostTopology.DefaultConfig.UsePlatformSpecificProtocols && Application.platform != RuntimePlatform.PS4)
        {
            throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
        }
        this.m_Channels = new P2PChannelBuffer[channelCount];
        for (int i = 0; i < channelCount; i++)
        {
            ChannelQOS channelQOS = hostTopology.DefaultConfig.Channels[i];
            int        bufferSize = packetSize;
            if (channelQOS.QOS == QosType.ReliableFragmented || channelQOS.QOS == QosType.UnreliableFragmented)
            {
                bufferSize = (int)(hostTopology.DefaultConfig.FragmentSize * 128);
            }
            this.m_Channels[i] = new P2PChannelBuffer(this, bufferSize, (byte)i, P2PConnection.IsReliableQoS(channelQOS.QOS));
        }
    }
Exemplo n.º 3
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.º 4
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.º 5
0
    public static P2PConnection GetConnection(int hostId, int connectionId)
    {
        P2PConnection connection = connections.FirstOrDefault(c =>
                                                              c.hostId == hostId &&
                                                              c.connectionId == connectionId);

        return(connection);
    }
Exemplo n.º 6
0
    public static P2PConnection GetConnection(string ip, int port)
    {
        P2PConnection connection = connections.FirstOrDefault(c =>
                                                              c.ip == ip &&
                                                              c.port == port);

        return(connection);
    }
Exemplo n.º 7
0
    private void SendBytesTo(int connection_id, byte[] bytes, int num_bytes, int channel_id)
    {
        P2PConnection p2PConnection = this.FindConnection(connection_id);

        if (p2PConnection == null)
        {
            return;
        }
        p2PConnection.SendBytes(bytes, num_bytes, channel_id);
    }
Exemplo n.º 8
0
    private void SendWriterTo(int connection_id, P2PNetworkWriter writer, int channel_id)
    {
        P2PConnection p2PConnection = this.FindConnection(connection_id);

        if (p2PConnection == null)
        {
            return;
        }
        p2PConnection.SendWriter(writer, channel_id);
    }
Exemplo n.º 9
0
    private void Disconnect(int connection_id)
    {
        P2PConnection p2PConnection = this.FindConnection(connection_id);

        if (p2PConnection == null)
        {
            return;
        }
        p2PConnection.Disconnect();
        this.m_Connections[connection_id] = null;
    }
Exemplo n.º 10
0
 private void UpdateConnections()
 {
     for (int i = 0; i < this.m_Connections.Count; i++)
     {
         P2PConnection p2PConnection = this.m_Connections[i];
         if (p2PConnection != null)
         {
             p2PConnection.FlushChannels();
         }
     }
 }
Exemplo n.º 11
0
 private void OnConnectInternal(P2PConnection conn)
 {
     if (P2PLogFilter.logDebug)
     {
         Debug.Log("P2PSession:OnConnectInternal");
     }
     if (conn.m_Peer.IsValid())
     {
         this.SendPeerInfoOnConnectionEstablished(conn);
     }
     Replicator.Singleton.OnPeerConnected(conn.m_Peer);
 }
Exemplo n.º 12
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.º 13
0
 private bool SetConnectionAtIndex(P2PConnection conn)
 {
     while (this.m_Connections.Count <= conn.m_ConnectionId)
     {
         this.m_Connections.Add(null);
     }
     if (this.m_Connections[conn.m_ConnectionId] != null)
     {
         return(false);
     }
     this.m_Connections[conn.m_ConnectionId] = conn;
     conn.SetHandlers(this.m_MessageHandlers);
     return(true);
 }
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
    private void CheckMasterOnDisconnection(P2PConnection disconnected_conn)
    {
        short hostId = this.LocalPeer.GetHostId();

        for (int i = 0; i < this.m_Connections.Count; i++)
        {
            if (this.m_Connections[i] != null && this.m_Connections[i] != disconnected_conn && this.m_Connections[i].m_Peer.GetHostId() < hostId)
            {
                hostId = this.m_Connections[i].m_Peer.GetHostId();
            }
        }
        if (P2PLogFilter.logDebug)
        {
            Debug.Log("P2PSession new master should be peer id: " + hostId);
        }
        this.m_AmIMaster = (this.LocalPeer.GetHostId() == hostId);
    }
Exemplo n.º 16
0
 public P2PChannelBuffer(P2PConnection conn, int bufferSize, byte cid, bool isReliable)
 {
     this.m_Connection            = conn;
     this.m_MaxPacketSize         = bufferSize - 100;
     this.m_CurrentPacket         = new P2PChannelPacket(this.m_MaxPacketSize, isReliable);
     this.m_ChannelId             = cid;
     this.m_MaxPendingPacketCount = 16;
     this.m_IsReliable            = isReliable;
     if (isReliable)
     {
         this.m_PendingPackets = new Queue <P2PChannelPacket>();
         if (P2PChannelBuffer.s_FreePackets == null)
         {
             P2PChannelBuffer.s_FreePackets = new List <P2PChannelPacket>();
         }
     }
 }
Exemplo n.º 17
0
 public void DisconnectAllConnections()
 {
     this.m_AmIMaster        = true;
     this.m_SpawnRefPosition = Vector3.zero;
     for (int i = 0; i < this.m_Connections.Count; i++)
     {
         P2PConnection p2PConnection = this.m_Connections[i];
         if (p2PConnection != null)
         {
             this.m_RemotePeersInternal.Remove(p2PConnection.m_Peer);
             this.OnDisconnected(p2PConnection);
             this.m_Connections[p2PConnection.m_ConnectionId] = null;
             p2PConnection.Disconnect();
             p2PConnection.Dispose();
         }
     }
     this.m_RemotePeersInternal.Clear();
     this.m_PendingPeers.Clear();
 }
Exemplo n.º 18
0
    public void SendWriterTo(P2PPeer peer, P2PNetworkWriter writer, int channel_id)
    {
        P2PConnection p2PConnection = this.FindConnection(peer);

        if (p2PConnection == null || !p2PConnection.m_IsReady)
        {
            if (P2PLogFilter.logError)
            {
                if (p2PConnection == null)
                {
                    Debug.LogError("Trying to send data without connection for peer: " + peer.GetHostId());
                    return;
                }
                Debug.LogError("Trying to send data on unready connection connection_id:" + p2PConnection.m_ConnectionId);
            }
            return;
        }
        p2PConnection.SendWriter(writer, channel_id);
    }
Exemplo n.º 19
0
    public bool SendToTransport(P2PConnection conn, int channelId)
    {
        bool result = true;
        byte b;

        if (!conn.TransportSend(this.m_Buffer, (int)((ushort)this.m_Position), channelId, out b) && (!this.m_IsReliable || b != 4))
        {
            if (P2PLogFilter.logError)
            {
                Debug.LogError(string.Concat(new object[]
                {
                    "Failed to send internal buffer channel:",
                    channelId,
                    " bytesToSend:",
                    this.m_Position
                }));
            }
            result = false;
        }
        if (b != 0)
        {
            if (this.m_IsReliable && b == 4)
            {
                return(false);
            }
            if (P2PLogFilter.logError)
            {
                Debug.LogError(string.Concat(new object[]
                {
                    "Send Error: ",
                    b,
                    " channel:",
                    channelId,
                    " bytesToSend:",
                    this.m_Position
                }));
            }
            result = false;
        }
        this.m_Position = 0;
        return(result);
    }
Exemplo n.º 20
0
    private void OnPeerDisconnect(P2PNetworkMessage net_msg)
    {
        P2PConnection connection = net_msg.m_Connection;
        P2PPeer       p2PPeer    = (connection != null) ? connection.m_Peer : null;

        if (p2PPeer != null)
        {
            Dictionary <GameObject, Relevance> .Enumerator enumerator = this.m_Components.GetEnumerator();
            while (enumerator.MoveNext())
            {
                KeyValuePair <GameObject, Relevance> keyValuePair = enumerator.Current;
                Relevance value = keyValuePair.Value;
                if (value)
                {
                    value.OnPeerDisconnected(p2PPeer);
                }
            }
            enumerator.Dispose();
        }
    }
Exemplo n.º 21
0
    private void HandleData(int connection_id, int channel_id, int received_size, byte error)
    {
        P2PConnection p2PConnection = this.FindConnection(connection_id);

        if (p2PConnection == null)
        {
            if (P2PLogFilter.logError)
            {
                Debug.LogError("P2PSession HandleData Unknown connectionId:" + connection_id);
            }
            return;
        }
        if (error != 0)
        {
            this.OnDataError(p2PConnection, error);
            return;
        }
        this.m_MsgReader.SeekZero();
        this.OnData(p2PConnection, received_size, channel_id);
    }
Exemplo n.º 22
0
    public override void Deserialize(NetworkReader reader)
    {
        lane = Convert.ToInt32(reader.ReadPackedUInt32());
        int successfulConnectionsCount = Convert.ToInt32(reader.ReadPackedUInt32());

        for (int i = 0; i < successfulConnectionsCount; i++)
        {
            byte[] bytes = reader.ReadBytesAndSize();
            string ip    = Encoding.UTF8.GetString(bytes);
            int    port  = Convert.ToInt32(reader.ReadPackedUInt32());

            P2PConnection connection = new P2PConnection(ip, port);
            connection.lane = Convert.ToInt32(reader.ReadPackedUInt32());

            successfulConnections.Add(connection);
        }
        r = Convert.ToInt32(reader.ReadPackedUInt32());
        g = Convert.ToInt32(reader.ReadPackedUInt32());
        b = Convert.ToInt32(reader.ReadPackedUInt32());
    }
Exemplo n.º 23
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.º 24
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.º 25
0
 public virtual void OnData(P2PConnection conn, int receivedSize, int channelId)
 {
     conn.TransportReceive(this.m_MsgBuffer, receivedSize, channelId);
 }
Exemplo n.º 26
0
    private void ConnectInternal(IP2PAddress address)
    {
        this.StartInternal();
        this.m_AmIMaster = false;
        P2PAddressUnet p2PAddressUnet = address as P2PAddressUnet;

        if (p2PAddressUnet != null)
        {
            if (p2PAddressUnet.m_IP.Equals("localhost"))
            {
                p2PAddressUnet.m_IP = "127.0.0.1";
            }
            else if (p2PAddressUnet.m_IP.IndexOf(":") != -1 && !P2PSession.IsValidIpV6(p2PAddressUnet.m_IP) && P2PLogFilter.logError)
            {
                Debug.LogError("Invalid ipv6 address " + p2PAddressUnet.m_IP);
            }
        }
        int networkConnectionId;

        if (this.m_UseSimulator)
        {
            int num = this.m_SimulatedLatency / 3;
            if (num < 1)
            {
                num = 1;
            }
            if (P2PLogFilter.logDebug)
            {
                Debug.Log(string.Concat(new object[]
                {
                    "Connect Using Simulator ",
                    this.m_SimulatedLatency / 3,
                    "/",
                    this.m_SimulatedLatency
                }));
            }
            ConnectionSimulatorConfig config = new ConnectionSimulatorConfig(num, this.m_SimulatedLatency, num, this.m_SimulatedLatency, this.m_PacketLoss);
            byte b;
            networkConnectionId = P2PTransportLayer.Instance.ConnectWithSimulator(address, out b, config);
        }
        else
        {
            byte b;
            networkConnectionId = P2PTransportLayer.Instance.Connect(address, out b);
        }
        P2PConnection p2PConnection = (P2PConnection)Activator.CreateInstance(typeof(P2PConnection));

        p2PConnection.SetHandlers(this.m_MessageHandlers);
        P2PPeer p2PPeer = null;

        for (int i = 0; i < this.m_PendingPeers.Count; i++)
        {
            if (this.m_PendingPeers[i].IsSameAddress(address))
            {
                p2PPeer = this.m_PendingPeers[i];
                this.m_PendingPeers.RemoveAt(i);
                break;
            }
        }
        if (p2PPeer == null)
        {
            p2PPeer           = new P2PPeer();
            p2PPeer.m_Address = address;
        }
        if (!this.m_RemotePeersInternal.Contains(p2PPeer))
        {
            this.m_RemotePeersInternal.Add(p2PPeer);
        }
        p2PConnection.Initialize(p2PPeer, networkConnectionId, P2PSession.s_HostTopology);
        this.SetConnectionAtIndex(p2PConnection);
        if (this.Status == P2PSession.ESessionStatus.Idle)
        {
            this.Status = P2PSession.ESessionStatus.Connecting;
        }
    }
Exemplo n.º 27
0
 public virtual void OnDisconnectError(P2PConnection conn, byte error)
 {
     Debug.LogError("OnDisconnectError error:" + error);
 }
Exemplo n.º 28
0
 public virtual void OnConnected(P2PConnection conn)
 {
     conn.m_IsReady = true;
     conn.InvokeHandlerNoData(32);
 }
Exemplo n.º 29
0
 public virtual void OnDisconnected(P2PConnection conn)
 {
     conn.InvokeHandlerNoData(33);
 }
Exemplo n.º 30
0
        public static async Task <bool> ListenForIncomingP2PConnectionsAsync(IPAddress ipInterfaceToBind, P2PNetworkParameters netParams)
        {
            if (!_listening)
            {
                if (netParams.ListenForPeers)
                {
                    try
                    {
                        LingerOption lo = new LingerOption(false, 0);
                        _socket             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        _socket.LingerState = lo;
                        _listening          = true;
                        _localEndPoint      = new IPEndPoint(ipInterfaceToBind, netParams.P2PListeningPort);
                        if (_socket.IsBound)
                        {
                            _socket.Close();
                        }
                        _socket.Bind(_localEndPoint);
                        _socket.Listen(1000);

                        if (netParams.UPnPMapPort)
                        {
                            //try upnp port forward mapping
                            await SetNATPortForwardingUPnPAsync(netParams.P2PListeningPort, netParams.P2PListeningPort);
                        }

                        _listenThread = new Thread(new ThreadStart(() =>
                        {
                            while (_listening)
                            {
                                try
                                {
                                    Socket newConnectedPeerSock = _socket.Accept();

                                    //if we haven't reached maximum specified to connect to us, allow the connection
                                    if (GetInboundP2PConnections().Count < P2PNetworkParameters.MaxIncomingP2PConnections)
                                    {
                                        //we've accepted a new peer create a new P2PConnection object to deal with them and we need to be sure to mark it as incoming so it gets stored appropriately
                                        P2PConnection p2pconnecting = new P2PConnection(((IPEndPoint)newConnectedPeerSock.RemoteEndPoint).Address, netParams, newConnectedPeerSock, Convert.ToUInt16(((IPEndPoint)newConnectedPeerSock.RemoteEndPoint).Port), true);
                                        p2pconnecting.ConnectToPeer(0);
                                    }
                                    else
                                    {
                                        newConnectedPeerSock.Close();
                                    }
                                }
                                catch (SocketException sex)
                                {
                                    //trap the exception "A blocking operation was interrupted by a call to WSACancelBlockingCall" thrown when we kill the listening socket but throw any others
                                    if (sex.ErrorCode != 10004)
                                    {
                                        //he said sex hehehehehehe
                                        throw sex;
                                    }
                                }
                            }
                        }));
                        _listenThread.IsBackground = true;
                        _listenThread.Start();
                    }
#if (!DEBUG)
                    catch
                    {
                        _listening = false;
                    }