Exemplo n.º 1
0
    void OnGUI()
    {
        GUILayout.Label("ProcessManager by krzys_h v0.4-beta");
        GUILayout.Label(hostId >= 0 ? "Server running on :" + serverPort : "Server not running");
        remoteIp   = GUILayout.TextField(remoteIp);
        remotePort = GUILayout.TextField(remotePort);
        if (GUILayout.Button("Connect [C]"))
        {
            StartClient();
        }

        string s = "";

        foreach (KeyValuePair <int, PlayerProcessManager> player in playerProcessManagers)
        {
            if (player.Key == 0)
            {
                s += player.Key + ": 127.0.0.1:" + serverPort;
            }
            else
            {
                string address;
                int    port;
                UnityEngine.Networking.Types.NetworkID network;
                UnityEngine.Networking.Types.NodeID    dstNode;
                byte error;
                NetworkTransport.GetConnectionInfo(hostId, player.Key, out address, out port, out network, out dstNode, out error);
                s += "\n" + player.Key + ": " + address + ":" + port;
            }
        }
        GUILayout.Label(s);
    }
Exemplo n.º 2
0
    public void f4resh()
    {
        int              outHostId = adapter.hostId;
        int              outConnectionId;
        int              outChannelId;
        string           outConnIp;
        int              outPort;
        int              receivedSize;
        byte             error;
        NetworkEventType evt;

        do
        {
            evt =
                NetworkTransport.ReceiveFromHost(adapter.hostId, out outConnectionId, out outChannelId, buffer, buffer.Length, out receivedSize, out error);
            if (error != 0)
            {
                Debug.Log("Receive error=" + error);
            }

            switch (evt)
            {
            case NetworkEventType.ConnectEvent:
            {
                Debug.Log("receiveChanneId=" + outChannelId);
                UnityEngine.Networking.Types.NetworkID outID;
                UnityEngine.Networking.Types.NodeID    outNode;
                NetworkTransport.GetConnectionInfo(outHostId, outConnectionId, out outConnIp, out outPort, out outID, out outNode, out error);
                adapter.connectionClient.Add(outConnectionId, new StrTxt(Instantiate(adapter.text), outConnIp, true));
                adapter.OnConnect(outHostId, outConnectionId, (NetworkError)error);
                break;
            }

            case NetworkEventType.DisconnectEvent:
            {
                adapter.OnDisconnect(outHostId, outConnectionId, (NetworkError)error);
                break;
            }

            case NetworkEventType.DataEvent:
            {
                OnData(outHostId, outConnectionId, outChannelId, buffer, receivedSize, (NetworkError)error);
                break;
            }

            case NetworkEventType.BroadcastEvent:
            {
                adapter.OnBroadcast(outHostId, buffer, receivedSize, (NetworkError)error);
                break;
            }

            case NetworkEventType.Nothing:
                break;

            default:
                Debug.LogError("Unknown network message type received: " + evt);
                break;
            }
        }while (evt != NetworkEventType.Nothing);
    }
Exemplo n.º 3
0
    void Update()
    {
        if (UnetServerStarted)
        {
            byte[]           recBuffer = new byte[1024];
            int              recHostId, connectionId, channelId, dataSize;
            byte             error;
            NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, 1024, out dataSize, out error);
            switch (recData)
            {
            case NetworkEventType.Nothing:
                break;

            case NetworkEventType.ConnectEvent:
                NetworkID id;
                NodeID    dstNode;
                string    clientIp;
                int       port;
                NetworkTransport.GetConnectionInfo(hostId, connectionId, out clientIp, out port, out id,
                                                   out dstNode, out error);
                ConnectionEvent?.Invoke(null,
                                        new UnetConnectionMsg(hostId, connectionId, channelId, clientIp.Split(':')[3], port));
                break;

            case NetworkEventType.DataEvent:
                string msg = System.Text.Encoding.Default.GetString(recBuffer);
                DataEvent?.Invoke(null, new UnetDataMsg(hostId, connectionId, channelId, msg));
                break;

            case NetworkEventType.DisconnectEvent:
                DisconnectionEvent?.Invoke(null, new UnetConnectionMsg(hostId, connectionId, channelId, "", 0));
                break;
            }
        }
    }
Exemplo n.º 4
0
    private void AddConnection(int connectionId)
    {
        string recAddress;
        int    port;

        UnityEngine.Networking.Types.NetworkID recNetId;
        UnityEngine.Networking.Types.NodeID    recNodeId;
        byte recError;

        NetworkTransport.GetConnectionInfo(socketId, connectionId, out recAddress, out port, out recNetId, out recNodeId, out recError);
        NetworkPlayer player = GetPlayer(recAddress);

        // Jugador existía y se reconecta.
        if (player != null)
        {
            player.connected    = true;
            player.connectionId = connectionId;
            SendMessageToClient(connectionId, "ChangeScene/" + player.room.sceneToLoad, true);
            timesScene1IsLoaded += 1;
            messageHandler.SendAllData(connectionId, player.room, true);
            UnityEngine.Debug.Log("Client " + connectionId + " reconnected");
            return;
        }

        //Jugador no existía y se crea uno nuevo.
        Room room = SearchRoom();

        if (room == null)
        {
            room = new Room(rooms.Count, this, messageHandler, maxJugadores);
            rooms.Add(room);
        }

        room.AddPlayer(connectionId, recAddress);
    }
Exemplo n.º 5
0
    public UnityNetDriverConnection(IntHashtable <UnityNetDriverConnection> connections, UnityNetDriver driver, INetDriverCallbacks callbacks, int socketId, int connectionId, int reliableChannel, int unreliableChannel)
    {
        _netDriver         = driver;
        this.callbacks     = callbacks;
        _socketID          = socketId;
        _connectionID      = connectionId;
        _unreliableChannel = unreliableChannel;
        _reliableChannel   = reliableChannel;
        this.connections   = connections;

        int    port;
        ulong  network;
        ushort node;
        byte   error;

        NetworkTransport.GetConnectionInfo(socketId, connectionId, out port, out network, out node, out error);

        byte[] ip = System.BitConverter.GetBytes(network);
        if (network == ulong.MaxValue)           // loopback
        {
            ip[0] = 127;
            ip[1] = 0;
            ip[2] = 0;
            ip[3] = 0;
        }
        _id = string.Format("{0}.{1}.{2}.{3}:{4}", ip[0], ip[1], ip[2], ip[3], port);
    }
    // Client connected so create cube for them
    void ClientConnected(int connectionId)
    {
        string    address;
        int       port;
        NetworkID network;
        NodeID    dstNode;
        byte      error;

        NetworkTransport.GetConnectionInfo(m_hostId, connectionId, out address, out port, out network, out dstNode, out error);

        // Create new object
        GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);

        obj.AddComponent <CharacterController>();
        // Set position
        obj.transform.position = new Vector3(UnityEngine.Random.Range(-5.0f, 5.0f), 0, UnityEngine.Random.Range(-5.0f, 5.0f));
        // Set color
        obj.GetComponent <Renderer>().material.color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value);

        ClientData cd = new ClientData();

        cd.connectionId = connectionId;
        cd.name         = new IPEndPoint(IPAddress.Parse(address), port).ToString();
        cd.obj          = obj;
        // Remember client
        clientList.Add(cd);
        Debug.Log(string.Format("Client {0} connected", cd.name));

        // Send all clients new info
        SendClientInformation();
    }
Exemplo n.º 7
0
    private void AddConnection(int connectionId)
    {
        int    port;
        byte   recError;
        string recAddress;

        UnityEngine.Networking.Types.NodeID    recNodeId;
        UnityEngine.Networking.Types.NetworkID recNetId;

        NetworkTransport.GetConnectionInfo(socketId, connectionId, out recAddress, out port, out recNetId, out recNodeId, out recError);
        NetworkPlayer player = GetPlayer(recAddress);

        // Jugador existía y se reconecta.
        if (player != null)
        {
            player.connected    = true;
            player.connectionId = connectionId;
            SendMessageToClient(connectionId, "ChangeScene/" + player.room.sceneToLoad, true);
            List <NetworkPlayer> players = player.room.players;
            foreach (NetworkPlayer connectedPlayer in players)
            {
                if (connectedPlayer.controlOverEnemies)
                {
                    SendMessageToClient(connectionId, "PlayerHasReturned/", true);
                    break;
                }
            }
            messageHandler.SendAllData(recAddress, player.room);
            player.room.SendControlEnemiesToClient(player, false);
            player.SendDataToRoomBoxManager();
            UnityEngine.Debug.Log("Client " + recAddress + " reconnected");
            return;
        }

        //Jugador no existía y se crea uno nuevo.
        Room room = SearchRoom();

        if (room == null)
        {
            roomCounter++;
            RoomLogger logger = null;
            if (lastDestroyedRoom != null)
            {
                logger            = lastDestroyedRoom.log;
                lastDestroyedRoom = null;
            }
            room = new Room(roomCounter, this, messageHandler, maxPlayers, logger);
            RoomManager rm = GameObject.FindGameObjectWithTag("RoomManager").GetComponent <RoomManager>();
            if (!rm)
            {
                UnityEngine.Debug.LogError("No se encontró RoomManager en ServerScene. uwu 1");
            }
            rm.AddNewRoom(room);
            rooms.Add(room);
        }

        room.AddPlayer(connectionId, recAddress);
    }
Exemplo n.º 8
0
        public bool GetConnectionInfo(int connectionId, out string address)
        {
            int       port;
            NetworkID networkId;
            NodeID    node;

            NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out address, out port, out networkId, out node, out error);
            return(true);
        }
Exemplo n.º 9
0
 public void GetConnectionInfo()
 {
     NetworkTransport.GetConnectionInfo(HostID, ConnectionID, out ServerPort, out NetworkID, out DstNode, out Error);
     Log.Server("Connection Info Report");
     Log.Line(" Port: " + ServerPort.ToString());
     Log.Line(" Network ID: " + NetworkID.ToString());
     Log.Line(" DstNode: " + DstNode.ToString());
     Log.Line(" Error: " + ((NetworkError)Error).ToString());
 }
Exemplo n.º 10
0
    public void GetConnectionInfo(int connection_id, out IP2PAddress address, out byte error)
    {
        address = new P2PAddressUnet();
        P2PAddressUnet p2PAddressUnet = (P2PAddressUnet)address;
        NetworkID      networkID;
        NodeID         nodeID;

        NetworkTransport.GetConnectionInfo((int)P2PSession.Instance.LocalPeer.GetLocalHostId(), connection_id, out p2PAddressUnet.m_IP, out p2PAddressUnet.m_Port, out networkID, out nodeID, out error);
    }
Exemplo n.º 11
0
        public string ClientGetAddress()
        {
            string    address = "";
            int       port;
            NetworkID networkId;
            NodeID    node;

            NetworkTransport.GetConnectionInfo(serverHostId, clientId, out address, out port, out networkId, out node, out error);
            return(address);
        }
Exemplo n.º 12
0
        public override string ServerGetClientAddress(int connectionId)
        {
            string    address = "";
            int       port;
            NetworkID networkId;
            NodeID    node;

            NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out address, out port, out networkId, out node, out error);
            return(address);
        }
Exemplo n.º 13
0
        //==============
        // Commands
        //==============
        public void Host(string[] values)
        {
            NetworkID network;
            NodeID    node;

            Networker.mode = NetworkerMode.Server;
            this.ParseAddress(values, ref this.hostIP, ref this.hostPort);
            this.SetupHost();
            NetworkTransport.GetConnectionInfo(this.socketID, this.socketID, out this.hostIP, out this.hostPort, out network, out node, out this.errorCode);
            Log.Show("[Server] Server created at " + this.hostIP + ":" + this.hostPort + ".");
        }
    private void Receive_Data_GameServerConnected(int connectionId, string[] splitData)
    {
        if (VerifySplitData(connectionId, splitData, 2))
        {
            string gameServerVersionNumber = splitData[1];

            if (VerifyConnectionVersionNumber(connectionId, gameServerVersionNumber) == false)                                  // Verify GameServer's VersionNumber
            {
                return;
            }

            // Get Connection Info
            string connectedIpAddress;
            int    connectedPort;
            UnityEngine.Networking.Types.NetworkID connectedNetId;
            UnityEngine.Networking.Types.NodeID    connectedNodeId;

            NetworkTransport.GetConnectionInfo(connectionData.hostId, connectionId, out connectedIpAddress, out connectedPort, out connectedNetId, out connectedNodeId, out connectionData.error);

            //connectedPort = int.Parse(splitData[1]);			// TODO: Security

            if (gameServers.Count == 0 || gameServers.Exists(gs => gs.connectionId == connectionId) == false)
            {
                // Get a new port for this GameServer
                int newPort = 0;

                foreach (KeyValuePair <int, bool> gameServerPort in gameServerPorts)
                {
                    if (gameServerPort.Value == true)                           // If the gameServerPort is open (true)
                    {
                        newPort = gameServerPort.Key;
                        break;
                    }
                }

                // Close this port so we don't send it to another GameServer
                gameServerPorts[newPort] = false;

                // Add a new GameServer to our list of GameServers
                UnityEngine.Debug.Log("Added new GameServer to servers list [ipAddress: " + connectedIpAddress + "] [connectionId: " + connectionId + "]");
                gameServers.Add(new ConnectedGameServer(connectedIpAddress, connectionId, newPort));                                // TODO: TryParse!

                // Send the GameServer it's specified port
                Send_Data_GameServerPort(connectionId);

                Send_Answer_GameServerDetails();
            }
            else
            {
                UnityEngine.Debug.LogError("Failed to add GameServer to servers list [ipAddress: " + connectedIpAddress + "] [connectionId: " + connectionId + "]");
                KickConnection(connectionId);
            }
        }
    }
Exemplo n.º 15
0
    public string GetConnectionDescription(int connectionId)
    {
        string    address;
        int       port;
        NetworkID network;
        NodeID    dstNode;
        byte      error;

        NetworkTransport.GetConnectionInfo(m_HostId, connectionId, out address, out port, out network, out dstNode, out error);
        return("UNET: " + address + ":" + port);
    }
Exemplo n.º 16
0
            static public ConnectionInfo GetConnectionInfoFromConnectionID(int coID)
            {
                ConnectionInfo info = new ConnectionInfo();

                UnityEngine.Networking.Types.NetworkID ID;
                UnityEngine.Networking.Types.NodeID    Node;
                byte error;

                NetworkTransport.GetConnectionInfo(HostID, coID, out info.IP, out info.Port, out ID, out Node, out error);
                return(info);
            }
Exemplo n.º 17
0
    void Update()
    {
        if (!string.IsNullOrEmpty(recvStr))
        {
            this.MultiSendMessage(recvStr);
            SocketRecMsg.text = recvStr;
            recvStr           = "";
        }

        if (!UnetEnabled)
        {
            return;
        }
        byte[]           recBuffer = new byte[1024];
        int              recHostId, connectionId, channelId, dataSize;
        byte             error;
        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, 1024, out dataSize, out error);

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

        case NetworkEventType.ConnectEvent:
            NetworkID id;
            NodeID    dstNode;
            string    clientIp;
            int       port;
            NetworkTransport.GetConnectionInfo(hostId, connectionId, out clientIp, out port, out id, out dstNode, out error);

            if (ConnectionEvent != null)
            {
                ConnectionEvent(this, new ConnectionMsg(hostId, connectionId, channelId, clientIp.Split(':')[3], port));
            }
            break;

        case NetworkEventType.DataEvent:
            string msg = System.Text.Encoding.Default.GetString(recBuffer);
            if (DataEvent != null)
            {
                DataEvent(this, new DataMsg(hostId, connectionId, channelId, msg));
            }
            break;

        case NetworkEventType.DisconnectEvent:
            if (DisconnectionEvent != null)
            {
                DisconnectionEvent(this, new ConnectionMsg(hostId, connectionId, channelId, "", 0));
            }
            break;
        }
    }
Exemplo n.º 18
0
    public bool NextEvent(ref TransportEvent res)
    {
        GameDebug.Assert(m_HostId > -1, "Trying to update transport with no host id");

        Profiler.BeginSample("UNETTransform.ReadData()");

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

        var ne = NetworkTransport.ReceiveFromHost(m_HostId, out connectionId, out channelId, m_ReadBuffer, m_ReadBuffer.Length, out receivedSize, out error);

        switch (ne)
        {
        default:
        case UnityEngine.Networking.NetworkEventType.Nothing:
            Profiler.EndSample();
            return(false);

        case UnityEngine.Networking.NetworkEventType.ConnectEvent:
        {
            string    address;
            int       port;
            NetworkID network;
            NodeID    dstNode;
            NetworkTransport.GetConnectionInfo(m_HostId, connectionId, out address, out port, out network, out dstNode, out error);
            GameDebug.Log("Incoming connection: " + connectionId + " (from " + address + ":" + port + ")");

            res.type         = TransportEvent.Type.Connect;
            res.connectionId = connectionId;
            break;
        }

        case UnityEngine.Networking.NetworkEventType.DisconnectEvent:
            res.type         = TransportEvent.Type.Disconnect;
            res.connectionId = connectionId;
            break;

        case UnityEngine.Networking.NetworkEventType.DataEvent:
            res.type         = TransportEvent.Type.Data;
            res.data         = m_ReadBuffer;
            res.dataSize     = receivedSize;
            res.connectionId = connectionId;
            break;
        }

        Profiler.EndSample();

        return(true);
    }
Exemplo n.º 19
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.º 20
0
    void ServerMessage(string message)
    {
        byte[] bytes = new byte[message.Length * sizeof(char)];
        System.Buffer.BlockCopy(message.ToCharArray(), 0, bytes, 0, bytes.Length);

        for (int i = 1; i <= MaxConnections; ++i)
        {
            NetworkTransport.GetConnectionInfo(HostID, i, out ServerPort, out NetworkID, out DstNode, out Error);

            if (Error == 0)
            {
                NetworkTransport.Send(HostID, i, Reliable, bytes, bytes.Length, out Error);
            }
        }
    }
Exemplo n.º 21
0
    /// <summary>
    /// Write out information about the connection with the given host id and connection id.
    /// </summary>
    /// <param name="hostId">Host identifier</param>
    /// <param name="connectionId">Connection identifier</param>
    public static void LogConnectionInfo(int hostId, int connectionId)
    {
        string address;
        int    port;

        UnityEngine.Networking.Types.NetworkID network;
        UnityEngine.Networking.Types.NodeID    dstNode;
        byte error;

        NetworkTransport.GetConnectionInfo(
            hostId, connectionId, out address, out port, out network,
            out dstNode, out error);

        Debug.LogFormat("Connection info: from IP {0}:{1}", address, port);
    }
Exemplo n.º 22
0
        public void SyncClient(byte[] data)
        {
            NetworkID network;
            NodeID    node;
            string    name   = data.ReadString(2);
            var       client = new NetworkerClient(this.receivedID, name);

            NetworkTransport.GetConnectionInfo(this.socketID, this.receivedID, out client.ip, out client.port, out network, out node, out this.errorCode);
            this.clients.Add(client);
            foreach (var history in this.eventHistory)
            {
                Networker.SendMessage(history, this.receivedID);
            }
            Networker.SendEventToClient("AddClient", this.receivedID.ToBytes().Append(name));
            Log.Show("[Server] Client " + this.receivedID + " identified as " + name + ".");
        }
Exemplo n.º 23
0
    void Update()
    {
        // Let user spawn a sphere if they want
        if (Input.GetKey(KeyCode.Space))
        {
            StartCoroutine(SpawnCoroutine());
        }

        // Remember who's connecting and disconnecting to us
        if (m_hostId == -1)
        {
            return;
        }
        int  connectionId;
        int  channelId;
        int  receivedSize;
        byte error;

        byte[]           buffer       = new byte[1500];
        NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(m_hostId, out connectionId, out channelId, buffer, buffer.Length, out receivedSize, out error);

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

        case NetworkEventType.ConnectEvent:
            string    address;
            int       port;
            NetworkID network;
            NodeID    dstNode;
            NetworkTransport.GetConnectionInfo(m_hostId, connectionId, out address, out port, out network, out dstNode, out error);
            connectList.Add(connectionId);
            Debug.Log(string.Format("Client {0} connected", new IPEndPoint(IPAddress.Parse(address), port).ToString()));
            break;

        case NetworkEventType.DisconnectEvent:
            connectList.Remove(connectionId);
            Debug.Log("Client disconnected");
            break;

        case NetworkEventType.DataEvent:
            Debug.Log(string.Format("Got data size {0}", receivedSize));
            break;
        }
    }
Exemplo n.º 24
0
    // Update is called once per frame
    void Update()
    {
        recBuffer = new byte[1024];
        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

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

        case NetworkEventType.ConnectEvent:
            NetworkID id;
            NodeID    dstNode;
            try
            {
                NetworkTransport.GetConnectionInfo(hostId, connectionId, out clientIp, out port, out id, out dstNode, out error);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            if (ConnectionEvent != null)
            {
                ConnectionEvent(this, new ConnectionMsg(hostId, connectionId, channelId, clientIp.Split(':')[3], port));
            }
            break;

        case NetworkEventType.DataEvent:
            string msg = System.Text.Encoding.Default.GetString(recBuffer);
            if (DataEvent != null)
            {
                DataEvent(this, new DataMsg(hostId, connectionId, channelId, msg));
            }
            break;

        case NetworkEventType.DisconnectEvent:
            if (DisconnectionEvent != null)
            {
                DisconnectionEvent(this, new ConnectionMsg(hostId, connectionId, channelId, "", 0));
            }
            break;
        }
    }
Exemplo n.º 25
0
            internal void OnConnected()
            {
                int       port;
                string    address;
                NetworkID networkID;
                NodeID    nodeID;
                byte      error;

                // Validates connection and gets info about the connection
                NetworkTransport.GetConnectionInfo(Host.Id, Id, out address, out port, out networkID, out nodeID, out error);
                if (error > 0)
                {
                    throw new NetworkException("Unable to get connection info, invalid connection id?", error);
                }

                //
                NetworkInfo = new NetworkInfo(address, port);
                IsConnected = true;
            }
Exemplo n.º 26
0
        /// <summary>
        /// Called by a router to create a network connection.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="hostId">The transport layer host id.</param>
        /// <param name="id">The transport layer connection id.</param>
        public Connection(Router router, int hostId, int id)
        {
            _meta         = new Meta();
            _router       = router;
            _hostId       = hostId;
            _id           = id;
            _disconnected = false;

            ulong  network;
            ushort dstNode;
            byte   error;

            _remoteAddress = NetworkTransport.GetConnectionInfo(hostId, id,
                                                                out _remotePort, out network, out dstNode, out error);
            if (error != (byte)NetworkError.Ok)
            {
                throw new TransportLayerException(error);
            }
        }
        public bool ImmediateStart(int socketId, int id)
        {
            if (_opened)
            {
                return(false);
            }
            _opened = true;

            Id        = id;
            _socketId = socketId;

            NetworkTransport.GetConnectionInfo(_socketId, Id, out string ip, out int port, out NetworkID network, out NodeID end, out byte error);
            ParseError("Failed to get connection info", error);

            Ip   = ip;
            Port = port;

            NetworkTransport.NotifyWhenConnectionReadyForSend(_socketId, Id, 1, out error);
            ParseError("Failed to request notify", error);

            return(true);
        }
Exemplo n.º 28
0
        private void OnConnectEvent()
        {
            string address;
            int    port;

            UnityEngine.Networking.Types.NetworkID network;
            UnityEngine.Networking.Types.NodeID    dstNode;

            NetworkTransport.GetConnectionInfo(_outHostId, _outConnectionId, out address, out port, out network,
                                               out dstNode, out _error);
            Debug.Log("NetworkServer received ConnectEvent. connectionId = " + _outConnectionId + " address = " +
                      address);

            if (!_connectionDictionary.ContainsKey(_outConnectionId))
            {
                _connectionDictionary.Add(_outConnectionId, new IPEndPoint(IPAddress.Parse(address), port));
            }
            else
            {
                Debug.Log("_connectionDictionary already ContainsKey for connectionId " + _outConnectionId);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Used by the server to add connections.
        /// </summary>
        /// <param name="connectionID"></param>
        protected virtual void OnClientConnected(int connectionID)
        {
            if (m_Connections == null)
            {
                m_Connections = new Dictionary <int, NetworkConnection>();
            }

            if (IsServer)
            {
                NetworkTransport.GetConnectionInfo(m_HostID, connectionID, out string addr, out _, out _, out _, out byte err);
                if ((NetworkError)err != NetworkError.Ok)
                {
                    DebugLogError(string.Format("Unable to retrieve connection info from client {0}. Error: {1}", connectionID, (NetworkError)err));
                    return;
                }

                DebugLog(string.Format("Client {0} connected from {1}.", connectionID, addr));

                m_Connections[connectionID] = new NetworkConnection(addr, connectionID);
                m_Connections[connectionID].Send(ReliableSequencedChannel, RemoteConnectMsg, GetRemoteConnectWriter(connectionID, true).ToArray());
            }
        }
Exemplo n.º 30
0
        private RemoteTerminalInfo RegisterRemoteTerminal(int connID, int hostID)
        {
            if (m_ConnectedTerminalInfoMap.ContainsKey(connID))
            {
                Debug.LogError("Connection ID: " + connID + " duplicated!!!");
                return(null);
            }

            int    remotePort;
            ulong  remoteNetwork;
            ushort remoteDstNode;
            byte   error;
            string remoteIP = NetworkTransport.GetConnectionInfo(hostID, connID,
                                                                 out remotePort, out remoteNetwork, out remoteDstNode, out error);

            if (m_ConnectedIpSet.Contains(remoteIP))
            {
                Debug.LogError("Remote Terminal: " + remoteIP + " is connected already!");
                return(null);
            }

            RemoteTerminalInfo info = new RemoteTerminalInfo()
            {
                HostID = hostID,
                ConnID = connID,
                IP     = remoteIP,
                Port   = remotePort
            };

            m_ConnectedTerminalInfoMap.Add(connID, info);
            m_ConnectedIpSet.Add(remoteIP);

            EvtDispatcher.Instance.Dispatch(NetworkEvt.EVT_REMOTE_TERMINAL_REGISTERED, info);

            Debug.Log(string.Format("<color=blue>Remote Terminal {0} is connected to host {1} with Connection ID {2} via port {3}</color>",
                                    remoteIP, hostID, connID, remotePort));
            return(info);
        }