コード例 #1
0
 public override void DisconnectLocalClient()
 {
     if (NetworkManager.Get().enableLogging)
     {
         Debug.Log("Transport Disconnect Local Client");
     }
     Unet.Disconnect(serverHostID, serverConnectionID, out byte error);
 }
コード例 #2
0
        public override void Init()
        {
            if (NetworkManager.Get().enableLogging)
            {
                Debug.Log("Unet init called");
            }
            messageBuffer = new byte[MessageBufferSize];

            Unet.Init();
        }
コード例 #3
0
        public override void DisconnectRemoteClient(ulong clientID)
        {
            if (NetworkManager.Get().enableLogging)
            {
                Debug.Log("Transport Disconnect Remote Client");
            }
            GetUnetConnectionDetails(clientID, out byte hostID, out ushort connectionID);

            Unet.Disconnect((int)hostID, (int)connectionID, out byte error);
        }
コード例 #4
0
        public override void StartServer()
        {
            if (NetworkManager.Get().enableLogging)
            {
                Debug.Log("Transport Start Server");
            }
            HostTopology topology = new HostTopology(GetConfig(), MaxConnections);

            if (SupportWebsocket)
            {
                int websocketHostID = Unet.AddWebsocketHost(topology, ServerWebsocketListenPort);
            }

            int normalHostID = Unet.AddHost(topology, ServerListenPort);
        }
コード例 #5
0
        public override void StartClient()
        {
            if (NetworkManager.Get().enableLogging)
            {
                Debug.Log("Transport Start Client");
            }
            //SocketTask task = SocketTask.Working;

            serverHostID       = Unet.AddHost(new HostTopology(GetConfig(), 1));
            serverConnectionID = Unet.Connect(serverHostID, address, port, 0, out byte error);

            NetworkError connectError = (NetworkError)error;

            if (connectError != NetworkError.Ok)
            {
                //Throw Start Client failed exception
                throw new NetworkException("Unet failed to start client with error '" + connectError + "'.");
            }
        }
コード例 #6
0
        public override void Send(ulong clientID, ArraySegment <byte> data, byte channel)
        {
            GetUnetConnectionDetails(clientID, out byte hostID, out ushort connectionID);

            byte[] buffer;

            if (data.Offset > 0)
            {
                // UNET cant handle this, do a copy

                if (messageBuffer.Length >= data.Count)
                {
                    buffer = messageBuffer;
                }
                else
                {
                    if (temporaryBufferReference != null && temporaryBufferReference.IsAlive && ((byte[])temporaryBufferReference.Target).Length >= data.Count)
                    {
                        buffer = (byte[])temporaryBufferReference.Target;
                    }
                    else
                    {
                        buffer = new byte[data.Count];
                        temporaryBufferReference = new WeakReference(buffer);
                    }
                }

                Buffer.BlockCopy(data.Array, data.Offset, buffer, 0, data.Count);
            }
            else
            {
                buffer = data.Array;
            }

            /*RelayTransport.*/
            Unet.Send(hostID, connectionID, m_UnetChannelLookup[channel], buffer, data.Count, out byte error);
        }
コード例 #7
0
        public static int AddHostWithSimulator(HostTopology topology, int minTimeout, int maxTimeout, int port)
        {
            string ip = null;

            return(NetworkTransport.AddHostWithSimulator(topology, minTimeout, maxTimeout, port, ip));
        }
コード例 #8
0
        public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error)
        {
            error = 0;
            byte[] array = new byte[]
            {
                95,
                36,
                19,
                246
            };
            if (endPoint == null)
            {
                throw new NullReferenceException("Null EndPoint provided");
            }
            if (endPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint" && endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint" && endPoint.GetType().FullName != "UnityEngine.PSVita.SceEndPoint")
            {
                throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint  required");
            }
            int result;

            if (endPoint.GetType().FullName == "UnityEngine.XboxOne.XboxOneEndPoint")
            {
                if (endPoint.AddressFamily != AddressFamily.InterNetworkV6)
                {
                    throw new ArgumentException("XboxOneEndPoint has an invalid family");
                }
                SocketAddress socketAddress = endPoint.Serialize();
                if (socketAddress.Size != 14)
                {
                    throw new ArgumentException("XboxOneEndPoint has an invalid size");
                }
                if (socketAddress[0] != 0 || socketAddress[1] != 0)
                {
                    throw new ArgumentException("XboxOneEndPoint has an invalid family signature");
                }
                if (socketAddress[2] != array[0] || socketAddress[3] != array[1] || socketAddress[4] != array[2] || socketAddress[5] != array[3])
                {
                    throw new ArgumentException("XboxOneEndPoint has an invalid signature");
                }
                byte[] array2 = new byte[8];
                for (int i = 0; i < array2.Length; i++)
                {
                    array2[i] = socketAddress[6 + i];
                }
                IntPtr intPtr = new IntPtr(BitConverter.ToInt64(array2, 0));
                if (intPtr == IntPtr.Zero)
                {
                    throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer");
                }
                byte[] array3 = new byte[2];
                Marshal.Copy(intPtr, array3, 0, array3.Length);
                AddressFamily addressFamily = (AddressFamily)(((int)array3[1] << 8) + (int)array3[0]);
                if (addressFamily != AddressFamily.InterNetworkV6)
                {
                    throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer");
                }
                result = NetworkTransport.Internal_ConnectEndPoint(hostId, intPtr, 128, exceptionConnectionId, out error);
            }
            else
            {
                SocketAddress socketAddress2 = endPoint.Serialize();
                if (socketAddress2.Size != 16)
                {
                    throw new ArgumentException("EndPoint has an invalid size");
                }
                if ((int)socketAddress2[0] != socketAddress2.Size)
                {
                    throw new ArgumentException("EndPoint has an invalid size value");
                }
                if (socketAddress2[1] != 2)
                {
                    throw new ArgumentException("EndPoint has an invalid family value");
                }
                byte[] array4 = new byte[16];
                for (int j = 0; j < array4.Length; j++)
                {
                    array4[j] = socketAddress2[j];
                }
                IntPtr intPtr2 = Marshal.AllocHGlobal(array4.Length);
                Marshal.Copy(array4, 0, intPtr2, array4.Length);
                int num = NetworkTransport.Internal_ConnectEndPoint(hostId, intPtr2, 16, exceptionConnectionId, out error);
                Marshal.FreeHGlobal(intPtr2);
                result = num;
            }
            return(result);
        }
コード例 #9
0
 public static void Init(GlobalConfig config)
 {
     NetworkTransport.InitWithParameters(new GlobalConfigInternal(config));
 }
コード例 #10
0
 public void SendPeerInfo()
 {
     if (this.m_HostMigration)
     {
         PeerListMessage        peerListMessage = new PeerListMessage();
         List <PeerInfoMessage> list            = new List <PeerInfoMessage>();
         for (int i = 0; i < NetworkServer.connections.Count; i++)
         {
             NetworkConnection networkConnection = NetworkServer.connections[i];
             if (networkConnection != null)
             {
                 PeerInfoMessage peerInfoMessage = new PeerInfoMessage();
                 string          address;
                 int             port;
                 NetworkID       networkID;
                 NodeID          nodeID;
                 byte            b;
                 NetworkTransport.GetConnectionInfo(NetworkServer.serverHostId, networkConnection.connectionId, out address, out port, out networkID, out nodeID, out b);
                 peerInfoMessage.connectionId = networkConnection.connectionId;
                 peerInfoMessage.port         = port;
                 if (i == 0)
                 {
                     peerInfoMessage.port    = NetworkServer.listenPort;
                     peerInfoMessage.isHost  = true;
                     peerInfoMessage.address = "<host>";
                 }
                 else
                 {
                     peerInfoMessage.address = address;
                     peerInfoMessage.isHost  = false;
                 }
                 List <PeerInfoPlayer> list2 = new List <PeerInfoPlayer>();
                 for (int j = 0; j < networkConnection.playerControllers.Count; j++)
                 {
                     PlayerController playerController = networkConnection.playerControllers[j];
                     if (playerController != null && playerController.unetView != null)
                     {
                         PeerInfoPlayer item;
                         item.netId = playerController.unetView.netId;
                         item.playerControllerId = playerController.unetView.playerControllerId;
                         list2.Add(item);
                     }
                 }
                 if (networkConnection.clientOwnedObjects != null)
                 {
                     foreach (NetworkInstanceId netId in networkConnection.clientOwnedObjects)
                     {
                         GameObject gameObject = NetworkServer.FindLocalObject(netId);
                         if (!(gameObject == null))
                         {
                             NetworkIdentity component = gameObject.GetComponent <NetworkIdentity>();
                             if (component.playerControllerId == -1)
                             {
                                 PeerInfoPlayer item2;
                                 item2.netId = netId;
                                 item2.playerControllerId = -1;
                                 list2.Add(item2);
                             }
                         }
                     }
                 }
                 if (list2.Count > 0)
                 {
                     peerInfoMessage.playerIds = list2.ToArray();
                 }
                 list.Add(peerInfoMessage);
             }
         }
         peerListMessage.peers = list.ToArray();
         for (int k = 0; k < NetworkServer.connections.Count; k++)
         {
             NetworkConnection networkConnection2 = NetworkServer.connections[k];
             if (networkConnection2 != null)
             {
                 peerListMessage.oldServerConnectionId = networkConnection2.connectionId;
                 networkConnection2.Send(11, peerListMessage);
             }
         }
     }
 }
コード例 #11
0
 public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error) =>
 NetworkTransport.Send(this.hostId, this.connectionId, channelId, bytes, numBytes, out error);
コード例 #12
0
        internal void ContinueConnect()
        {
            byte error;

            // regular non-relay connect
            if (m_UseSimulator)
            {
                int simLatency = m_SimulatedLatency / 3;
                if (simLatency < 1)
                {
                    simLatency = 1;
                }

                if (LogFilter.logDebug)
                {
                    Debug.Log("Connect Using Simulator " + (m_SimulatedLatency / 3) + "/" + m_SimulatedLatency);
                }
                var simConfig = new ConnectionSimulatorConfig(
                    simLatency,
                    m_SimulatedLatency,
                    simLatency,
                    m_SimulatedLatency,
                    m_PacketLoss);

                m_ClientConnectionId = m_UseRelay ? RelayTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, RelayTransport.RelayAddress, RelayTransport.RelayPort, 0, out error, simConfig) : NetworkTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, 0, out error, simConfig);
            }
            else
            {
                m_ClientConnectionId = m_UseRelay ? RelayTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, RelayTransport.RelayAddress, RelayTransport.RelayPort, 0, out error) : NetworkTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, 0, out error);
            }

            m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
            m_Connection.SetHandlers(m_MessageHandlers);
            m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
        }
コード例 #13
0
 public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
 {
     return(m_UseRelay ? RelayTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error) : NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error));
 }
コード例 #14
0
        public NetworkClient StartClient(ConnectionConfig config, int hostPort)
        {
            InitializeSingleton();

            if (m_RunInBackground)
            {
                Application.runInBackground = true;
            }

            isNetworkActive = true;

            if (m_GlobalConfig != null)
            {
                NetworkTransport.Init(m_GlobalConfig);
            }

            client          = new NetworkClient();
            client.hostPort = hostPort;

            if (config != null)
            {
                if ((config.UsePlatformSpecificProtocols) && (Application.platform != RuntimePlatform.PS4) && (Application.platform != RuntimePlatform.PSP2))
                {
                    throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
                }

                client.Configure(config, 1);
            }
            else
            {
                if (m_CustomConfig && m_ConnectionConfig != null)
                {
                    m_ConnectionConfig.Channels.Clear();
                    for (int i = 0; i < m_Channels.Count; i++)
                    {
                        m_ConnectionConfig.AddChannel(m_Channels[i]);
                    }
                    if ((m_ConnectionConfig.UsePlatformSpecificProtocols) && (Application.platform != RuntimePlatform.PS4) && (Application.platform != RuntimePlatform.PSP2))
                    {
                        throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
                    }
                    client.Configure(m_ConnectionConfig, m_MaxConnections);
                }
            }

            RegisterClientMessages(client);
            if (m_EndPoint != null)
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("NetworkManager StartClient using provided SecureTunnel");
                }
                client.Connect(m_EndPoint);
            }
            else
            {
                if (string.IsNullOrEmpty(m_NetworkAddress))
                {
                    if (LogFilter.logError)
                    {
                        Debug.LogError("Must set the Network Address field in the manager");
                    }
                    return(null);
                }
                if (LogFilter.logDebug)
                {
                    Debug.Log("NetworkManager StartClient address:" + m_NetworkAddress + " port:" + m_NetworkPort);
                }

                client.Connect(m_NetworkAddress, m_NetworkPort);
            }

            OnStartClient(client);
            s_Address = m_NetworkAddress;
            return(client);
        }
コード例 #15
0
        internal virtual void Update()
        {
            if (this.m_ClientId == -1)
            {
                return;
            }
            switch (this.m_AsyncConnect)
            {
            case NetworkClient.ConnectState.None:
                break;

            case NetworkClient.ConnectState.Resolving:
                break;

            case NetworkClient.ConnectState.Resolved:
                this.m_AsyncConnect = NetworkClient.ConnectState.Connecting;
                this.ContinueConnect();
                break;

            case NetworkClient.ConnectState.Disconnected:
                break;

            case NetworkClient.ConnectState.Failed:
                this.GenerateConnectError(11);
                this.m_AsyncConnect = NetworkClient.ConnectState.Disconnected;
                break;

            default:
                if (this.m_Connection != null && (int)Time.time != this.m_StatResetTime)
                {
                    this.m_Connection.ResetStats();
                    this.m_StatResetTime = (int)Time.time;
                }
                NetworkEventType fromHost;
                do
                {
                    int  num1 = 0;
                    int  connectionId;
                    int  channelId;
                    int  receivedSize;
                    byte error;
                    fromHost = NetworkTransport.ReceiveFromHost(this.m_ClientId, out connectionId, out channelId, this.m_MsgBuffer, (int)(ushort)this.m_MsgBuffer.Length, out receivedSize, out error);
                    if (fromHost != NetworkEventType.Nothing && LogFilter.logDev)
                    {
                        Debug.Log((object)("Client event: host=" + (object)this.m_ClientId + " event=" + (object)fromHost + " error=" + (object)error));
                    }
                    switch (fromHost)
                    {
                    case NetworkEventType.DataEvent:
                        if ((int)error != 0)
                        {
                            this.GenerateDataError((int)error);
                            return;
                        }
                        NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short)29, "msg", 1);
                        this.m_MsgReader.SeekZero();
                        this.m_Connection.TransportRecieve(this.m_MsgBuffer, receivedSize, channelId);
                        goto case NetworkEventType.Nothing;

                    case NetworkEventType.ConnectEvent:
                        if (LogFilter.logDebug)
                        {
                            Debug.Log((object)"Client connected");
                        }
                        if ((int)error != 0)
                        {
                            this.GenerateConnectError((int)error);
                            return;
                        }
                        this.m_AsyncConnect = NetworkClient.ConnectState.Connected;
                        this.m_Connection.InvokeHandlerNoData((short)32);
                        goto case NetworkEventType.Nothing;

                    case NetworkEventType.DisconnectEvent:
                        if (LogFilter.logDebug)
                        {
                            Debug.Log((object)"Client disconnected");
                        }
                        this.m_AsyncConnect = NetworkClient.ConnectState.Disconnected;
                        if ((int)error != 0 && (int)error != 6)
                        {
                            this.GenerateDisconnectError((int)error);
                        }
                        ClientScene.HandleClientDisconnect(this.m_Connection);
                        if (this.m_Connection != null)
                        {
                            this.m_Connection.InvokeHandlerNoData((short)33);
                            goto case NetworkEventType.Nothing;
                        }
                        else
                        {
                            goto case NetworkEventType.Nothing;
                        }

                    case NetworkEventType.Nothing:
                        int num2;
                        if ((num2 = num1 + 1) >= 500)
                        {
                            if (LogFilter.logDebug)
                            {
                                Debug.Log((object)("MaxEventsPerFrame hit (" + (object)500 + ")"));
                                goto label_34;
                            }
                            else
                            {
                                goto label_34;
                            }
                        }
                        else
                        {
                            continue;
                        }

                    default:
                        if (LogFilter.logError)
                        {
                            Debug.LogError((object)("Unknown network message type received: " + (object)fromHost));
                            goto case NetworkEventType.Nothing;
                        }
                        else
                        {
                            goto case NetworkEventType.Nothing;
                        }
                    }
                }while (this.m_ClientId != -1 && fromHost != NetworkEventType.Nothing);
label_34:
                if (this.m_Connection == null || this.m_AsyncConnect != NetworkClient.ConnectState.Connected)
                {
                    break;
                }
                this.m_Connection.FlushChannels();
                break;
            }
        }
コード例 #16
0
        public void Connect(EndPoint secureTunnelEndPoint)
        {
            bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint);

            PrepareForConnect(usePlatformSpecificProtocols);

            if (LogFilter.logDebug)
            {
                Debug.Log("Client Connect to remoteSockAddr");
            }

            if (secureTunnelEndPoint == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Connect failed: null endpoint passed in");
                }
                m_AsyncConnect = ConnectState.Failed;
                return;
            }

            // Make sure it's either IPv4 or IPv6
            if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6");
                }
                m_AsyncConnect = ConnectState.Failed;
                return;
            }

            // Make sure it's an Endpoint we know what to do with
            string endPointType = secureTunnelEndPoint.GetType().FullName;

            if (endPointType == "System.Net.IPEndPoint")
            {
                IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint;
                Connect(tmp.Address.ToString(), tmp.Port);
                return;
            }
            if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint") && (endPointType != "UnityEngine.PSVita.SceEndPoint"))
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)");
                }
                m_AsyncConnect = ConnectState.Failed;
                return;
            }

            byte error = 0;

            // regular non-relay connect
            m_RemoteEndPoint = secureTunnelEndPoint;
            m_AsyncConnect   = ConnectState.Connecting;

            try
            {
                m_ClientConnectionId = m_UseRelay ? RelayTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, RelayTransport.RelayAddress, RelayTransport.RelayPort, 0, out error) : NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error);
            }
            catch (Exception ex)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Connect failed: Exception when trying to connect to EndPoint: " + ex);
                }
                m_AsyncConnect = ConnectState.Failed;
                return;
            }
            if (m_ClientConnectionId == 0)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Connect failed: Unable to connect to EndPoint (" + error + ")");
                }
                m_AsyncConnect = ConnectState.Failed;
                return;
            }

            m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
            m_Connection.SetHandlers(m_MessageHandlers);
            m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
        }
コード例 #17
0
        void PrepareForConnect(bool usePlatformSpecificProtocols)
        {
            SetActive(true);
            RegisterSystemHandlers(false);

            if (m_HostTopology == null)
            {
                var config = new ConnectionConfig();
                config.AddChannel(QosType.ReliableSequenced);
                config.AddChannel(QosType.Unreliable);
                config.UsePlatformSpecificProtocols = usePlatformSpecificProtocols;
                m_HostTopology = new HostTopology(config, 8);
            }

            if (m_UseSimulator)
            {
                int minTimeout = (m_SimulatedLatency / 3) - 1;
                if (minTimeout < 1)
                {
                    minTimeout = 1;
                }
                int maxTimeout = m_SimulatedLatency * 3;

                if (LogFilter.logDebug)
                {
                    Debug.Log("AddHost Using Simulator " + minTimeout + "/" + maxTimeout);
                }
                m_ClientId = m_UseRelay ? RelayTransport.AddHostWithSimulator(m_HostTopology, minTimeout, maxTimeout, m_HostPort, false, RelayTransport.RelayAddress, RelayTransport.RelayPort) : NetworkTransport.AddHostWithSimulator(m_HostTopology, minTimeout, maxTimeout, m_HostPort);
            }
            else
            {
                m_ClientId = m_UseRelay ? RelayTransport.AddHost(m_HostTopology, m_HostPort, false, RelayTransport.RelayAddress, RelayTransport.RelayPort) :  NetworkTransport.AddHost(m_HostTopology, m_HostPort);
            }
        }
コード例 #18
0
        public bool Listen(int serverListenPort, HostTopology topology)
        {
            m_HostTopology = topology;
            Initialize();
            m_ListenPort = serverListenPort;

            if (m_UseWebSockets)
            {
                m_ServerHostId = m_UseRelay ? RelayTransport.AddWebsocketHost(m_HostTopology, serverListenPort, true) : NetworkTransport.AddWebsocketHost(m_HostTopology, serverListenPort);
            }
            else
            {
                m_ServerHostId = m_UseRelay ? RelayTransport.AddWebsocketHost(m_HostTopology, serverListenPort, true) : NetworkTransport.AddHost(m_HostTopology, serverListenPort);
            }

            if (m_ServerHostId == -1)
            {
                return(false);
            }

            if (LogFilter.logDebug)
            {
                Debug.Log("NetworkServerSimple listen " + m_ListenPort);
            }
            return(true);
        }
コード例 #19
0
        internal virtual void Update()
        {
            if (m_ClientId == -1)
            {
                return;
            }

            switch (m_AsyncConnect)
            {
            case ConnectState.None:
            case ConnectState.Resolving:
            case ConnectState.Disconnected:
                return;

            case ConnectState.Failed:
                GenerateConnectError((int)NetworkError.DNSFailure);
                m_AsyncConnect = ConnectState.Disconnected;
                return;

            case ConnectState.Resolved:
                m_AsyncConnect = ConnectState.Connecting;
                ContinueConnect();
                return;

            case ConnectState.Connecting:
            case ConnectState.Connected:
            {
                break;
            }
            }

            if (m_Connection != null)
            {
                if ((int)Time.time != m_StatResetTime)
                {
                    m_Connection.ResetStats();
                    m_StatResetTime = (int)Time.time;
                }
            }

            int numEvents = 0;
            NetworkEventType networkEvent;

            do
            {
                int  connectionId;
                int  channelId;
                int  receivedSize;
                byte error;

                networkEvent = m_UseRelay ? RelayTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error) : NetworkTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error);
                if (m_Connection != null)
                {
                    m_Connection.lastError = (NetworkError)error;
                }

                if (networkEvent != NetworkEventType.Nothing)
                {
                    if (LogFilter.logDev)
                    {
                        Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error);
                    }
                }

                switch (networkEvent)
                {
                case NetworkEventType.ConnectEvent:

                    if (LogFilter.logDebug)
                    {
                        Debug.Log("Client connected");
                    }

                    if (error != 0)
                    {
                        GenerateConnectError(error);
                        return;
                    }

                    m_AsyncConnect = ConnectState.Connected;
                    m_Connection.InvokeHandlerNoData(MsgType.Connect);
                    break;

                case NetworkEventType.DataEvent:
                    if (error != 0)
                    {
                        GenerateDataError(error);
                        return;
                    }

#if UNITY_EDITOR
                    UnityEditor.NetworkDetailStats.IncrementStat(
                        UnityEditor.NetworkDetailStats.NetworkDirection.Incoming,
                        MsgType.LLAPIMsg, "msg", 1);
#endif

                    m_MsgReader.SeekZero();
                    m_Connection.TransportReceive(m_MsgBuffer, receivedSize, channelId);
                    break;

                case NetworkEventType.DisconnectEvent:
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("Client disconnected");
                    }

                    m_AsyncConnect = ConnectState.Disconnected;

                    if (error != 0)
                    {
                        if ((NetworkError)error != NetworkError.Timeout)
                        {
                            GenerateDisconnectError(error);
                        }
                    }
                    ClientScene.HandleClientDisconnect(m_Connection);
                    if (m_Connection != null)
                    {
                        m_Connection.InvokeHandlerNoData(MsgType.Disconnect);
                    }
                    break;

                case NetworkEventType.Nothing:
                    break;

                default:
                    if (LogFilter.logError)
                    {
                        Debug.LogError("Unknown network message type received: " + networkEvent);
                    }
                    break;
                }

                if (++numEvents >= k_MaxEventsPerFrame)
                {
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")");
                    }
                    break;
                }
                if (m_ClientId == -1)
                {
                    break;
                }
            }while (networkEvent != NetworkEventType.Nothing);

            if (m_Connection != null && m_AsyncConnect == ConnectState.Connected)
            {
                m_Connection.FlushChannels();
            }
        }
コード例 #20
0
        public void Update()
        {
            if (m_ServerHostId == -1)
            {
                return;
            }

            int  connectionId;
            int  channelId;
            int  receivedSize;
            byte error;

            var networkEvent = NetworkEventType.DataEvent;

            if (m_RelaySlotId != -1)
            {
                networkEvent = NetworkTransport.ReceiveRelayEventFromHost(m_ServerHostId, out error);
                if (NetworkEventType.Nothing != networkEvent)
                {
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("NetGroup event:" + networkEvent);
                    }
                }
                if (networkEvent == NetworkEventType.ConnectEvent)
                {
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("NetGroup server connected");
                    }
                }
                if (networkEvent == NetworkEventType.DisconnectEvent)
                {
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("NetGroup server disconnected");
                    }
                }
            }

            do
            {
                networkEvent = m_UseRelay ? RelayTransport.ReceiveFromHost(m_ServerHostId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error) : NetworkTransport.ReceiveFromHost(m_ServerHostId, out connectionId, out channelId, m_MsgBuffer, (int)m_MsgBuffer.Length, out receivedSize, out error);
                if (networkEvent != NetworkEventType.Nothing)
                {
                    if (LogFilter.logDev)
                    {
                        Debug.Log("Server event: host=" + m_ServerHostId + " event=" + networkEvent + " error=" + error);
                    }
                }

                switch (networkEvent)
                {
                case NetworkEventType.ConnectEvent:
                {
                    HandleConnect(connectionId, error);
                    break;
                }

                case NetworkEventType.DataEvent:
                {
                    HandleData(connectionId, channelId, receivedSize, error);
                    break;
                }

                case NetworkEventType.DisconnectEvent:
                {
                    HandleDisconnect(connectionId, error);
                    break;
                }

                case NetworkEventType.Nothing:
                    break;

                default:
                    if (LogFilter.logError)
                    {
                        Debug.LogError("Unknown network message type received: " + networkEvent);
                    }
                    break;
                }
            }while (networkEvent != NetworkEventType.Nothing);

            UpdateConnections();
        }
コード例 #21
0
        public void SendPeerInfo()
        {
            if (!m_HostMigration)
            {
                return;
            }

            var listMsg   = new PeerListMessage();
            var addresses = new List <PeerInfoMessage>();

            for (int i = 0; i < NetworkServer.connections.Count; i++)
            {
                var conn = NetworkServer.connections[i];
                if (conn != null)
                {
                    var peerInfo = new PeerInfoMessage();

                    string    address;
                    int       port;
                    NetworkID networkId;
                    NodeID    node;
                    byte      error2;
                    NetworkTransport.GetConnectionInfo(NetworkServer.serverHostId, conn.connectionId, out address, out port, out networkId, out node, out error2);

                    peerInfo.connectionId = conn.connectionId;
                    peerInfo.port         = port;
                    if (i == 0)
                    {
                        peerInfo.port    = NetworkServer.listenPort;
                        peerInfo.isHost  = true;
                        peerInfo.address = "<host>";
                    }
                    else
                    {
                        peerInfo.address = address;
                        peerInfo.isHost  = false;
                    }
                    var playerIds = new List <PeerInfoPlayer>();
                    foreach (var player in conn.playerControllers)
                    {
                        if (player != null && player.unetView != null)
                        {
                            PeerInfoPlayer info;
                            info.netId = player.unetView.netId;
                            info.playerControllerId = player.unetView.playerControllerId;
                            playerIds.Add(info);
                        }
                    }

                    if (conn.clientOwnedObjects != null)
                    {
                        foreach (var netId in conn.clientOwnedObjects)
                        {
                            var obj = NetworkServer.FindLocalObject(netId);
                            if (obj == null)
                            {
                                continue;
                            }

                            var objUV = obj.GetComponent <NetworkIdentity>();
                            if (objUV.playerControllerId != -1)
                            {
                                // already added players
                                continue;
                            }

                            PeerInfoPlayer info;
                            info.netId = netId;
                            info.playerControllerId = -1;
                            playerIds.Add(info);
                        }
                    }
                    if (playerIds.Count > 0)
                    {
                        peerInfo.playerIds = playerIds.ToArray();
                    }
                    addresses.Add(peerInfo);
                }
            }

            listMsg.peers = addresses.ToArray();

            // (re)send all peers to all peers (including the new one)
            for (int i = 0; i < NetworkServer.connections.Count; i++)
            {
                var conn = NetworkServer.connections[i];
                if (conn != null)
                {
                    listMsg.oldServerConnectionId = conn.connectionId;
                    conn.Send(MsgType.NetworkInfo, listMsg);
                }
            }
        }
コード例 #22
0
        bool StartServer(MatchInfo info, ConnectionConfig config, int maxConnections)
        {
            InitializeSingleton();

            OnStartServer();

            if (m_RunInBackground)
            {
                Application.runInBackground = true;
            }

            NetworkCRC.scriptCRCCheck   = scriptCRCCheck;
            NetworkServer.useWebSockets = m_UseWebSockets;

            if (m_GlobalConfig != null)
            {
                NetworkTransport.Init(m_GlobalConfig);
            }

            // passing a config overrides setting the connectionConfig property
            if (m_CustomConfig && m_ConnectionConfig != null && config == null)
            {
                m_ConnectionConfig.Channels.Clear();
                foreach (var c in m_Channels)
                {
                    m_ConnectionConfig.AddChannel(c);
                }
                NetworkServer.Configure(m_ConnectionConfig, m_MaxConnections);
            }

            if (config != null)
            {
                NetworkServer.Configure(config, maxConnections);
            }

            if (info != null)
            {
                if (!NetworkServer.Listen(info, m_NetworkPort))
                {
                    if (LogFilter.logError)
                    {
                        Debug.LogError("StartServer listen failed.");
                    }
                    return(false);
                }
            }
            else
            {
                if (m_ServerBindToIP && !string.IsNullOrEmpty(m_ServerBindAddress))
                {
                    if (!NetworkServer.Listen(m_ServerBindAddress, m_NetworkPort))
                    {
                        if (LogFilter.logError)
                        {
                            Debug.LogError("StartServer listen on " + m_ServerBindAddress + " failed.");
                        }
                        return(false);
                    }
                }
                else
                {
                    if (!NetworkServer.Listen(m_NetworkPort))
                    {
                        if (LogFilter.logError)
                        {
                            Debug.LogError("StartServer listen failed.");
                        }
                        return(false);
                    }
                }
            }

            // this must be after Listen(), since that registers the default message handlers
            RegisterServerMessages();

            if (LogFilter.logDebug)
            {
                Debug.Log("NetworkManager StartServer port:" + m_NetworkPort);
            }
            isNetworkActive = true;

            // Only change scene if the requested online scene is not blank, and is not already loaded
            string loadedSceneName = SceneManager.GetSceneAt(0).name;

            if (m_OnlineScene != "" && m_OnlineScene != loadedSceneName && m_OnlineScene != m_OfflineScene)
            {
                ServerChangeScene(m_OnlineScene);
            }
            else
            {
                NetworkServer.SpawnObjects();
            }
            return(true);
        }
コード例 #23
0
 public static void Init()
 {
     NetworkTransport.InitWithNoParameters();
 }
コード例 #24
0
        public NetworkClient StartClient(MatchInfo info, ConnectionConfig config)
        {
            InitializeSingleton();

            matchInfo = info;
            if (m_RunInBackground)
            {
                Application.runInBackground = true;
            }

            isNetworkActive = true;

            if (m_GlobalConfig != null)
            {
                NetworkTransport.Init(m_GlobalConfig);
            }

            client = new NetworkClient();

            if (config != null)
            {
                if ((config.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4))
                {
                    throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
                }

                client.Configure(config, 1);
            }
            else
            {
                if (m_CustomConfig && m_ConnectionConfig != null)
                {
                    m_ConnectionConfig.Channels.Clear();
                    foreach (var c in m_Channels)
                    {
                        m_ConnectionConfig.AddChannel(c);
                    }
                    if ((m_ConnectionConfig.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4))
                    {
                        throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
                    }
                    client.Configure(m_ConnectionConfig, m_MaxConnections);
                }
            }

            RegisterClientMessages(client);
            if (matchInfo != null)
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("NetworkManager StartClient match: " + matchInfo);
                }
                client.Connect(matchInfo);
            }
            else if (m_EndPoint != null)
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("NetworkManager StartClient using provided SecureTunnel");
                }
                client.Connect(m_EndPoint);
            }
            else
            {
                if (string.IsNullOrEmpty(m_NetworkAddress))
                {
                    if (LogFilter.logError)
                    {
                        Debug.LogError("Must set the Network Address field in the manager");
                    }
                    return(null);
                }
                if (LogFilter.logDebug)
                {
                    Debug.Log("NetworkManager StartClient address:" + m_NetworkAddress + " port:" + m_NetworkPort);
                }

                if (m_UseSimulator)
                {
                    client.ConnectWithSimulator(m_NetworkAddress, m_NetworkPort, m_SimulatedLatency, m_PacketLossPercentage);
                }
                else
                {
                    client.Connect(m_NetworkAddress, m_NetworkPort);
                }
            }

#if ENABLE_UNET_HOST_MIGRATION
            if (m_MigrationManager != null)
            {
                m_MigrationManager.Initialize(client, matchInfo);
            }
#endif

            OnStartClient(client);
            s_Address = m_NetworkAddress;
            return(client);
        }
コード例 #25
0
 public static int ConnectToNetworkPeer(int hostId, string address, int port, int exceptionConnectionId, int relaySlotId, NetworkID network, SourceID source, NodeID node, out byte error)
 {
     return(NetworkTransport.ConnectToNetworkPeer(hostId, address, port, exceptionConnectionId, relaySlotId, network, source, node, 0, 0f, out error));
 }
コード例 #26
0
        /// <summary>
        ///   <para>This sends the set of peers in the game to all the peers in the game.</para>
        /// </summary>
        public void SendPeerInfo()
        {
            if (!this.m_HostMigration)
            {
                return;
            }
            PeerListMessage        peerListMessage     = new PeerListMessage();
            List <PeerInfoMessage> peerInfoMessageList = new List <PeerInfoMessage>();

            for (int index = 0; index < NetworkServer.connections.Count; ++index)
            {
                NetworkConnection connection = NetworkServer.connections[index];
                if (connection != null)
                {
                    PeerInfoMessage peerInfoMessage = new PeerInfoMessage();
                    string          address;
                    int             port;
                    NetworkID       network;
                    NodeID          dstNode;
                    byte            error;
                    NetworkTransport.GetConnectionInfo(NetworkServer.serverHostId, connection.connectionId, out address, out port, out network, out dstNode, out error);
                    peerInfoMessage.connectionId = connection.connectionId;
                    peerInfoMessage.port         = port;
                    if (index == 0)
                    {
                        peerInfoMessage.port    = NetworkServer.listenPort;
                        peerInfoMessage.isHost  = true;
                        peerInfoMessage.address = "<host>";
                    }
                    else
                    {
                        peerInfoMessage.address = address;
                        peerInfoMessage.isHost  = false;
                    }
                    List <PeerInfoPlayer> peerInfoPlayerList = new List <PeerInfoPlayer>();
                    using (List <PlayerController> .Enumerator enumerator = connection.playerControllers.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            PlayerController current = enumerator.Current;
                            if (current != null && (Object)current.unetView != (Object)null)
                            {
                                PeerInfoPlayer peerInfoPlayer;
                                peerInfoPlayer.netId = current.unetView.netId;
                                peerInfoPlayer.playerControllerId = current.unetView.playerControllerId;
                                peerInfoPlayerList.Add(peerInfoPlayer);
                            }
                        }
                    }
                    if (connection.clientOwnedObjects != null)
                    {
                        using (HashSet <NetworkInstanceId> .Enumerator enumerator = connection.clientOwnedObjects.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                NetworkInstanceId current     = enumerator.Current;
                                GameObject        localObject = NetworkServer.FindLocalObject(current);
                                if (!((Object)localObject == (Object)null) && (int)localObject.GetComponent <NetworkIdentity>().playerControllerId == -1)
                                {
                                    PeerInfoPlayer peerInfoPlayer;
                                    peerInfoPlayer.netId = current;
                                    peerInfoPlayer.playerControllerId = (short)-1;
                                    peerInfoPlayerList.Add(peerInfoPlayer);
                                }
                            }
                        }
                    }
                    if (peerInfoPlayerList.Count > 0)
                    {
                        peerInfoMessage.playerIds = peerInfoPlayerList.ToArray();
                    }
                    peerInfoMessageList.Add(peerInfoMessage);
                }
            }
            peerListMessage.peers = peerInfoMessageList.ToArray();
            for (int index = 0; index < NetworkServer.connections.Count; ++index)
            {
                NetworkConnection connection = NetworkServer.connections[index];
                if (connection != null)
                {
                    peerListMessage.oldServerConnectionId = connection.connectionId;
                    connection.Send((short)11, (MessageBase)peerListMessage);
                }
            }
        }
コード例 #27
0
        public static int AddHost(HostTopology topology, int port)
        {
            string ip = null;

            return(NetworkTransport.AddHost(topology, port, ip));
        }
コード例 #28
0
        public bool ReconnectToNewHost(string serverIp, int serverPort)
        {
            if (!NetworkClient.active)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - NetworkClient must be active");
                }
                return(false);
            }

            if (m_Connection == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - no old connection exists");
                }
                return(false);
            }

            if (LogFilter.logInfo)
            {
                Debug.Log("NetworkClient Reconnect " + serverIp + ":" + serverPort);
            }

            ClientScene.HandleClientDisconnect(m_Connection);
            ClientScene.ClearLocalPlayers();

            m_Connection.Disconnect();
            m_Connection = null;
            m_ClientId   = m_UseRelay ? RelayTransport.AddHost(m_HostTopology, m_HostPort, false, RelayTransport.RelayAddress, RelayTransport.RelayPort) : NetworkTransport.AddHost(m_HostTopology, m_HostPort);

            string hostnameOrIp = serverIp;

            m_ServerPort = serverPort;

            //TODO: relay reconnect

            /*
             * if (Match.NetworkMatch.matchSingleton != null)
             * {
             *  hostnameOrIp = Match.NetworkMatch.matchSingleton.address;
             *  m_ServerPort = Match.NetworkMatch.matchSingleton.port;
             * }*/

            if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer)
            {
                m_ServerIp     = hostnameOrIp;
                m_AsyncConnect = ConnectState.Resolved;
            }
            else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost"))
            {
                m_ServerIp     = "127.0.0.1";
                m_AsyncConnect = ConnectState.Resolved;
            }
            else
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("Async DNS START:" + hostnameOrIp);
                }
                m_AsyncConnect = ConnectState.Resolving;
                Dns.BeginGetHostAddresses(hostnameOrIp, new AsyncCallback(GetHostAddressesCallback), this);
            }
            return(true);
        }
コード例 #29
0
 public static void GetBroadcastConnectionInfo(int hostId, out string address, out int port, out byte error)
 {
     address = NetworkTransport.GetBroadcastConnectionInfo(hostId, out port, out error);
 }
コード例 #30
0
        public bool ReconnectToNewHost(EndPoint secureTunnelEndPoint)
        {
            if (!NetworkClient.active)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - NetworkClient must be active");
                }
                return(false);
            }

            if (m_Connection == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - no old connection exists");
                }
                return(false);
            }

            if (LogFilter.logInfo)
            {
                Debug.Log("NetworkClient Reconnect to remoteSockAddr");
            }

            ClientScene.HandleClientDisconnect(m_Connection);
            ClientScene.ClearLocalPlayers();

            m_Connection.Disconnect();
            m_Connection = null;
            m_ClientId   = m_UseRelay ? RelayTransport.AddHost(m_HostTopology, m_HostPort, false, RelayTransport.RelayAddress, RelayTransport.RelayPort) : NetworkTransport.AddHost(m_HostTopology, m_HostPort);

            if (secureTunnelEndPoint == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect failed: null endpoint passed in");
                }
                m_AsyncConnect = ConnectState.Failed;
                return(false);
            }

            // Make sure it's either IPv4 or IPv6
            if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6");
                }
                m_AsyncConnect = ConnectState.Failed;
                return(false);
            }

            // Make sure it's an Endpoint we know what to do with
            string endPointType = secureTunnelEndPoint.GetType().FullName;

            if (endPointType == "System.Net.IPEndPoint")
            {
                IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint;
                Connect(tmp.Address.ToString(), tmp.Port);
                return(m_AsyncConnect != ConnectState.Failed);
            }
            if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint"))
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)");
                }
                m_AsyncConnect = ConnectState.Failed;
                return(false);
            }

            byte error = 0;

            // regular non-relay connect
            m_RemoteEndPoint = secureTunnelEndPoint;
            m_AsyncConnect   = ConnectState.Connecting;

            try
            {
                m_ClientConnectionId = m_UseRelay ? RelayTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, RelayTransport.RelayAddress, RelayTransport.RelayPort, 0, out error) : NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error);
            }
            catch (Exception ex)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect failed: Exception when trying to connect to EndPoint: " + ex);
                }
                m_AsyncConnect = ConnectState.Failed;
                return(false);
            }
            if (m_ClientConnectionId == 0)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect failed: Unable to connect to EndPoint (" + error + ")");
                }
                m_AsyncConnect = ConnectState.Failed;
                return(false);
            }

            m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
            m_Connection.SetHandlers(m_MessageHandlers);
            m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
            return(true);
        }