示例#1
0
            private static void ConnectCallback(object sender, EventArgs e)
            {
                try
                {
                    if (AlgorithmRates == null || _niceHashData == null)
                    {
                        _niceHashData  = new NiceHashData();
                        AlgorithmRates = _niceHashData.NormalizedSma();
                    }
                    //send login
                    var version = "NHML/" + Application.ProductVersion;
                    var login   = new nicehash_login
                    {
                        version = version
                    };
                    var loginJson = JsonConvert.SerializeObject(login);
                    SendData(loginJson);

                    DeviceStatus_Tick(null); // Send device to populate rig stats

                    OnConnectionEstablished.Emit(null, EventArgs.Empty);
                }
                catch (Exception er)
                {
                    Helpers.ConsolePrint("SOCKET", er.ToString());
                }
            }
        private static void SocketOnOnConnectionEstablished(object sender, EventArgs e)
        {
            DeviceStatus_Tick(null); // Send device to populate rig stats
            LoadSMA();               //for first run
            string ghv = GetVersion("");

            Helpers.ConsolePrint("GITHUB", ghv);
            SetVersion(ghv);
            OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
        }
示例#3
0
        public void Connect(IPEndPoint hostEndpoint, OnConnectionEstablished onConnectionEstablished = null,
                            OnConnectionFailure onConnectionFailure = null, OnDisconnected onDisconnected = null)
        {
            var connectionId = _transporter.Connect(hostEndpoint);

            _connections[connectionId] = new ConnectionRegistration {
                OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished,
                OnDisconnected          = onDisconnected ?? EmptyOnDisconnected
            };
        }
示例#4
0
        /// <summary>
        /// Achtung: Nicht Teil von ICommunication
        /// </summary>
        public void Open()
        {
            lock (_SerialPortLock) {
                if (!_port.IsOpen)
                {
                    _port.Open();
                }
            }

            OnConnectionEstablished?.Invoke(this);
            StartRead();
        }
        private void Login(object sender, EventArgs e)
        {
            try
            {
                var loginJson = JsonConvert.SerializeObject(_login);
                SendData(loginJson);

                OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
            } catch (Exception er)
            {
                NHM.Common.Logger.Info("SOCKET", er.Message);
            }
        }
        // loops receiving any messages
        private async Task ReceiveLoop(string address, int port, CancellationToken cancellationToken)
        {
            // connect
            await _tcpClient.ConnectAsync(address, port);

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (!_tcpClient.Connected)
            {
                OnClientDisconnected?.Invoke(new MessageEventArgs("Failed to connect"));
                return;
            }
            _controlStream = _tcpClient.GetStream();
            _controlWriter = new StreamWriter(_controlStream, Encoding.Default);
            OnConnectionEstablished?.Invoke(new MessageEventArgs("Connected"));

            // loop receiving data
            while (!cancellationToken.IsCancellationRequested)
            {
                if (!_tcpClient.Connected)
                {
                    OnClientDisconnected?.Invoke(new MessageEventArgs("Failed to connect"));
                    return;
                }

                int length;
                try {
                    length = await _controlStream.ReadAsync(_dataBuffer, 0, _dataBuffer.Length, cancellationToken);
                } catch (OperationCanceledException) {
                    return;
                }

                string message = Encoding.Default.GetString(_dataBuffer, 0, length);
                if (!string.IsNullOrEmpty(message) || _tcpClient.IsSocketConnected())
                {
                    await Store.TcpReceive.SendAsync(message);
                }
                else
                {
                    _tcpClient.Client.Disconnect(true);
                    OnClientDisconnected?.Invoke(new MessageEventArgs("Disconnected."));
                }
            }
        }
        public void Connect(IPEndPoint hostEndpoint,
                            OnConnectionEstablished onConnectionEstablished = null,
                            OnConnectionFailure onConnectionFailure         = null,
                            OnDisconnected onDisconnected = null)
        {
            var connectionRegistration = new ConnectionRegistration();

            connectionRegistration.Timestamp               = Time.realtimeSinceStartup;
            connectionRegistration.ConnectionId            = ConnectionId.NoConnection;
            connectionRegistration.PublicEndpoint          = hostEndpoint;
            connectionRegistration.OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished;
            connectionRegistration.OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure;
            connectionRegistration.OnDisconnected          = onDisconnected ?? EmptyOnDisconnected;

            var punchId = _natPunchClient.Punch(hostEndpoint, OnPunchSuccess, OnPunchFailure);

            _punchAttempts.Add(punchId, connectionRegistration);
        }
示例#8
0
        public ConnectionId Connect(IPEndPoint hostEndpoint,
                                    ApprovalSecret approvalSecret,
                                    OnConnectionEstablished onConnectionEstablished = null,
                                    OnConnectionFailure onConnectionFailure         = null,
                                    OnDisconnected onDisconnected = null)
        {
            var connectionId = _connectionIdPool.Take();

            _transporter.Connect(connectionId, approvalSecret, hostEndpoint);
            _connections[connectionId] = new ConnectionRegistration {
                Endpoint = hostEndpoint,
                OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished,
                OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure,
                OnDisconnected          = onDisconnected ?? EmptyOnDisconnected,
                Status = ConnectionStatus.Pending,
            };
            return(connectionId);
        }
        private void ConnectCallback(object sender, EventArgs e)
        {
            try
            {
                //send login
                var version = "NHML/" + Application.ProductVersion;
                var login   = new NicehashLogin
                {
                    version = version
                };
                var loginJson = JsonConvert.SerializeObject(login);
                SendData(loginJson);

                OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
            } catch (Exception er)
            {
                Helpers.ConsolePrint("SOCKET", er.ToString());
            }
        }
示例#10
0
        public void Connect()
        {
            try
            {
                _log.Info($"Connecting to {_gateway}:{_port}...");
                _tcpClient = new TcpClient(_gateway, _port)
                {
                    NoDelay = true
                };
            }
            catch (Exception ex)
            {
                _log.Error($"Connecting to {_gateway}:{_port} :: {ex}");
                throw;
            }

            _sslStream = new SslStream(_tcpClient.GetStream(), false, ValidateServerCertificate, null);
            try
            {
                _sslStream.AuthenticateAsClient(_gateway);
            }
            catch (Exception ex)
            {
                _log.Error($"_sslStream.AuthenticateAsClient({_gateway}) :: {ex}");
                _tcpClient.Dispose();
                throw;
            }

            if (!_sslStream.IsAuthenticated)
            {
                _log.Error($"Cannot establish secure connection to {_gateway}:{_port}");
                return;
            }

            Start_Listening_Thread();
            Start_Sender_Thread();
            Start_KeepAlive_Thread();

            _log.Info($"Connection established to {_gateway}:{_port}");

            OnConnectionEstablished?.Invoke(this, null);
        }
            private static void ConnectCallback(object sender, EventArgs e)
            {
                try {
                    if (AlgorithmRates == null)
                    {
                        // Populate SMA first (for port etc)
                        AlgorithmRates = BaseNiceHashSMA.BaseNiceHashSMADict;
                    }
                    //send login
                    var version = "NHML/" + Application.ProductVersion;
                    var login   = new nicehash_login();
                    login.version = version;
                    var loginJson = JsonConvert.SerializeObject(login);
                    SendData(loginJson);

                    OnConnectionEstablished.Emit(null, EventArgs.Empty);
                } catch (Exception er) {
                    Helpers.ConsolePrint("SOCKET", er.ToString());
                }
            }
示例#12
0
        private async Task InitConnection()
        {
            OnConnectionEstablished?.Invoke(this, System.EventArgs.Empty);

            var publicKey = await webApi.GetRequest <GetPublicKeyResponse>("jdev/sys/getPublicKey");;

            _pubKey = Convert.FromBase64String(publicKey.Data.PublicKey.Replace("-----END CERTIFICATE-----", "").Replace("-----BEGIN CERTIFICATE-----", ""));
            string stringDataToEncrypt;

            SecureRandom random = new SecureRandom();

            _aesKey = GenerateAesKey(LoxoneUuid);

            _aesIv = new byte[128 / 8];
            random.NextBytes(_aesIv);

            stringDataToEncrypt = $"{_aesKey.ToHex(false)}:{_aesIv.ToHex(false)}";

            Asn1Object  obj = Asn1Object.FromByteArray(_pubKey);
            DerSequence publicKeySequence = (DerSequence)obj;

            DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
            DerSequence  publicKeyDer     = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());

            DerInteger modulus  = (DerInteger)publicKeyDer[0];
            DerInteger exponent = (DerInteger)publicKeyDer[1];

            RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            encryptEngine.Init(true, keyParameters);

            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringDataToEncrypt);
            byte[] encryptedData = encryptEngine.ProcessBlock(dataToEncrypt, 0, dataToEncrypt.Length);

            var publicKeySelf = Convert.ToBase64String(encryptedData);

            _connectionState = ConnectionState.ExchangeKeys;

            _webSocket.Send($"jdev/sys/keyexchange/{publicKeySelf}");
        }
示例#13
0
 public void JoinServer(IPEndPoint endPoint,
                        int clientPort = -1,
                        OnConnectionEstablished onEstablished = null,
                        OnConnectionFailure onFailure         = null, OnDisconnected onDisconnected = null)
 {
     Shutdown();
     _isJoinInProgress = true;
     _isSingleplayer   = false;
     _coroutineScheduler.Run(_networkClient.Join(endPoint,
                                                 clientPort,
                                                 (connectionId, endpoint) => {
         _authorityConnectionId = connectionId;
         _isJoinInProgress      = false;
         if (onEstablished != null)
         {
             onEstablished(connectionId, endPoint);
         }
     },
                                                 onFailure,
                                                 onDisconnected));
 }
示例#14
0
        public NetServer(IPEndPoint endpoint, int maxConnections)
        {
            this.Endpoint = endpoint;

            this.server = new NetManager(listener, maxConnections, "Phinix")
            {
                PingInterval      = 5000,
                DisconnectTimeout = 30000
            };
            this.connectedPeers = new Dictionary <string, NetPeer>();

            // Subscribe to events
            listener.PeerConnectedEvent += (peer) =>
            {
                // Add or update the peer's connection
                string connectionId = peer.ConnectId.ToString("X");
                if (connectedPeers.ContainsKey(connectionId))
                {
                    connectedPeers[connectionId] = peer;
                }
                else
                {
                    connectedPeers.Add(connectionId, peer);
                }

                // Raise the connection established event for this peer
                OnConnectionEstablished?.Invoke(this, new ConnectionEventArgs(connectionId));
            };
            listener.PeerDisconnectedEvent += (peer, info) =>
            {
                // Remove the peer's connection
                string connectionId = peer.ConnectId.ToString("X");
                connectedPeers.Remove(connectionId);

                // Raise the connection established event for this peer
                OnConnectionClosed?.Invoke(this, new ConnectionEventArgs(connectionId));
            };
        }
示例#15
0
            private static void ConnectCallback(object sender, EventArgs e)
            {
                try
                {
                    NHSmaData.InitializeIfNeeded();
                    //send login
                    var version = "NHML/" + Application.ProductVersion;
                    var login   = new nicehash_login
                    {
                        version = version
                    };
                    var loginJson = JsonConvert.SerializeObject(login);
                    SendData(loginJson);

                    DeviceStatus_Tick(null); // Send device to populate rig stats

                    OnConnectionEstablished.Emit(null, EventArgs.Empty);
                }
                catch (Exception er)
                {
                    Helpers.ConsolePrint("SOCKET", er.ToString());
                }
            }
        public ConnectionId Connect(IPEndPoint hostEndpoint,
                                    ApprovalSecret approvalSecret,
                                    OnConnectionEstablished onConnectionEstablished = null,
                                    OnConnectionFailure onConnectionFailure         = null,
                                    OnDisconnected onDisconnected = null)
        {
            var connectionId           = _connectionIdPool.Take();
            var connectionRegistration = _connectionRegistrationPool.Take();

            connectionRegistration.Instance.Timestamp               = Time.realtimeSinceStartup;
            connectionRegistration.Instance.ConnectionId            = connectionId;
            connectionRegistration.Instance.ApprovalSecret          = approvalSecret;
            connectionRegistration.Instance.PublicEndpoint          = hostEndpoint;
            connectionRegistration.Instance.OnConnectionEstablished = onConnectionEstablished ?? EmptyOnConnectionEstablished;
            connectionRegistration.Instance.OnConnectionFailure     = onConnectionFailure ?? EmptyOnConnectionFailure;
            connectionRegistration.Instance.OnDisconnected          = onDisconnected ?? EmptyOnDisconnected;

            var punchId = _natPunchClient.Punch(hostEndpoint, OnPunchSuccess, OnPunchFailure);

            _punchAttempts.Add(punchId, connectionRegistration);

            return(connectionId);
        }
示例#17
0
        private static void SocketOnOnConnectionEstablished(object sender, EventArgs e)
        {
            DeviceStatus_Tick(null); // Send device to populate rig stats

            OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
        }
 private void Subsribe()
 {
     _manager.RdpViewer.OnApplicationClose          += delegate(object application) { OnApplicationClose?.Invoke(application); };
     _manager.RdpViewer.OnApplicationOpen           += delegate(object application) { OnApplicationOpen?.Invoke(application); };
     _manager.RdpViewer.OnApplicationUpdate         += delegate(object application) { OnApplicationUpdate?.Invoke(application); };
     _manager.RdpViewer.OnAttendeeConnected         += delegate(object attendee) { OnAttendeeConnected?.Invoke(attendee); };
     _manager.RdpViewer.OnAttendeeDisconnected      += delegate(object info) { OnAttendeeDisconnected?.Invoke(info); };
     _manager.RdpViewer.OnAttendeeUpdate            += delegate(object attendee) { OnAttendeeUpdate?.Invoke(attendee); };
     _manager.RdpViewer.OnChannelDataReceived       += delegate(object channel, int id, string data) { OnChannelDataReceived?.Invoke(channel, id, data); };
     _manager.RdpViewer.OnChannelDataSent           += delegate(object channel, int id, int sent) { OnChannelDataSent?.Invoke(channel, id, sent); };
     _manager.RdpViewer.OnConnectionAuthenticated   += delegate(object sender, EventArgs args) { OnConnectionAuthenticated?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionEstablished     += delegate(object sender, EventArgs args) { OnConnectionEstablished?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionFailed          += delegate(object sender, EventArgs args) { OnConnectionFailed?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionTerminated      += delegate(int reason, int info) { OnConnectionTerminated?.Invoke(reason, info); };
     _manager.RdpViewer.OnControlLevelChangeRequest += delegate(object attendee, CTRL_LEVEL level) { OnControlLevelChangeRequest?.Invoke(attendee, level); };
     _manager.RdpViewer.OnError                        += delegate(object info) { OnError?.Invoke(info); };
     _manager.RdpViewer.OnFocusReleased                += delegate(int direction) { OnFocusReleased?.Invoke(direction); };
     _manager.RdpViewer.OnGraphicsStreamPaused         += delegate(object sender, EventArgs args) { OnGraphicsStreamPaused?.Invoke(sender, args); };
     _manager.RdpViewer.OnGraphicsStreamResumed        += delegate(object sender, EventArgs args) { OnGraphicsStreamResumed?.Invoke(sender, args); };
     _manager.RdpViewer.OnSharedDesktopSettingsChanged += delegate(int width, int height, int colordepth) { OnSharedDesktopSettingsChanged?.Invoke(width, height, colordepth); };
     _manager.RdpViewer.OnSharedRectChanged            += delegate(int left, int top, int right, int bottom) { OnSharedRectChanged?.Invoke(left, top, right, bottom); };
     _manager.RdpViewer.OnWindowClose                  += delegate(object window) { OnWindowClose?.Invoke(window); };
     _manager.RdpViewer.OnWindowOpen                   += delegate(object window) { OnWindowOpen?.Invoke(window); };
     _manager.RdpViewer.OnWindowUpdate                 += delegate(object window) { OnWindowUpdate?.Invoke(window); };
 }
示例#19
0
        /// <summary>
        /// Dequeues all the messages from Discord and invokes appropriate methods. This will process the message and update the internal state before invoking the events. Returns the messages that were invoked and in the order they were invoked.
        /// </summary>
        /// <returns>Returns the messages that were invoked and in the order they were invoked.</returns>
        public IMessage[] Invoke()
        {
            //Dequeue all the messages and process them
            IMessage[] messages = connection.DequeueMessages();
            for (int i = 0; i < messages.Length; i++)
            {
                //Do a bit of pre-processing
                IMessage message = messages[i];
                HandleMessage(message);

                //Invoke the appropriate methods
                switch (message.Type)
                {
                case MessageType.Ready:
                    if (OnReady != null)
                    {
                        OnReady.Invoke(this, message as ReadyMessage);
                    }
                    break;

                case MessageType.Close:
                    if (OnClose != null)
                    {
                        OnClose.Invoke(this, message as CloseMessage);
                    }
                    break;

                case MessageType.Error:
                    if (OnError != null)
                    {
                        OnError.Invoke(this, message as ErrorMessage);
                    }
                    break;

                case MessageType.PresenceUpdate:
                    if (OnPresenceUpdate != null)
                    {
                        OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                    }
                    break;

                case MessageType.ConnectionEstablished:
                    if (OnConnectionEstablished != null)
                    {
                        OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                    }
                    break;

                case MessageType.ConnectionFailed:
                    if (OnConnectionFailed != null)
                    {
                        OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                    }
                    break;

                default:
                    //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                    Console.WriteLine($"Message was queued with no appropriate handle! {message.Type}");
                    break;
                }
            }

            //Finally, return the messages
            return(messages);
        }
示例#20
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    PresenceMessage pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                ReadyMessage rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    JoinRequestMessage jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    SubscribeMessage sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    UnsubscribeMessage unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
示例#21
0
        public IEnumerator <WaitCommand> Join(IPEndPoint endPoint,
                                              int clientPort = -1,
                                              OnConnectionEstablished onEstablished = null,
                                              OnConnectionFailure onFailure         = null,
                                              OnDisconnected onDisconnected         = null)
        {
            _outstandingPings.Clear();
            _frameId          = 0;
            _isJoinInProgress = true;

            var    sessionIdResult = new AsyncResult <JoinResponse>();
            string password        = null;

            _masterServerClient.Client.Join(endPoint, password, (statusCode, s) => {
                sessionIdResult.SetResult(s);
            });

            while (!sessionIdResult.IsResultAvailable)
            {
                yield return(WaitCommand.WaitForNextFrame);
            }

            if (sessionIdResult.Result != null)
            {
                _sessionId = sessionIdResult.Result.SessionId;

                var netConfig = new NetPeerConfiguration(NetworkConfig.GameId);
                // Kind of arbitrary, we need to have enough room for connection attempts
                // and cancellation running simultaneously but we don't need to have an unlimited number
                netConfig.MaximumConnections = 16;
                if (clientPort > -1)
                {
                    netConfig.Port = clientPort;
                }
                _transporter.Open(netConfig);

                var approvalSecret = new ApprovalSecret(_sessionId.Value.Value);
                _hostConnectionId = _networkSystems.ConnectionManager.Connect(endPoint,
                                                                              approvalSecret,
                                                                              (connId, endpoint) => {
                    _isJoinInProgress = false;
                    OnConnectionEstablished(connId, endpoint);
                    if (onEstablished != null)
                    {
                        onEstablished(connId, endpoint);
                    }
                },
                                                                              (endpoint, exception) => {
                    _isJoinInProgress = false;
                    OnConnectionFailure(endpoint, exception);
                    if (onFailure != null)
                    {
                        onFailure(endpoint, exception);
                    }
                },
                                                                              connId => {
                    _isJoinInProgress = false;
                    OnDisconnected(connId);
                    if (onDisconnected != null)
                    {
                        onDisconnected(connId);
                    }
                });
            }
            else
            {
                OnConnectionFailure(endPoint, new Exception("Master server did not allow join on " + endPoint));
            }
        }
示例#22
0
    public void Connect(IPEndPoint remoteEndPoint, OnConnectionEstablished onEstablished,
                        OnConnectionFailure onFailure, OnDisconnected onDisconnected)
    {
        _ramnet.MessageRouter.ClearHandlers();
        _ramnet.MessageRouter
        .RegisterHandler <BasicMessage.Pong>(OnServerClockSync)
        .RegisterHandler <BasicMessage.ReplicatePreExistingObject>((connectionId, endpoint, message) => {
            Debug.Log("replicating existing instance " + message.GlobalObjectId);
            var instance = _ramnet.PreExistingObjects[message.GlobalObjectId];
            Debug.Log("instance found: " + instance);
            _ramnet.ReplicatedObjectStore.ReplicateExistingInstance(message.ObjectRole, connectionId, instance,
                                                                    message.NetworkObjectId, message.GlobalObjectId);
        })
        .RegisterHandler <BasicMessage.CreateObject>((connectionId, endpoint, message, reader) => {
            var replicatedObject = _ramnet.ReplicatedObjectStore.AddReplicatedInstance(
                message.ObjectType,
                message.ObjectRole,
                message.ObjectId,
                connectionId);
            Debug.Log("Creating object with id " + message.ObjectId, replicatedObject.GameObject);
            _ramnet.ReplicatedObjectStore.DispatchMessages(connectionId, message.ObjectId,
                                                           message.AdditionalData, message.AdditionalData.LengthBytes);
            replicatedObject.Activate();
            if (message.ObjectType == ObjectTypes.Player && message.ObjectRole.IsOwner())
            {
                _camera.Target = replicatedObject.GameObject.GetComponent <PlayerSimulation>();
            }
        })
        .RegisterHandler <BasicMessage.ToObject>((connectionId, endpoint, message, reader) => {
            _ramnet.ReplicatedObjectStore.DispatchMessage(connectionId, message.ReceiverId,
                                                          reader);
        })
        .RegisterHandler <BasicMessage.DeleteObject>((connectionId, endpoint, message, reader) => {
            _ramnet.ReplicatedObjectStore.RemoveReplicatedInstance(connectionId, message.ObjectId);
        });
        _ramnet.GroupRouter.ClearConnectionHandlers();

        if (_transporter.Status == TransporterStatus.Closed)
        {
            var transportConfig = new NetPeerConfiguration("RigidbodyParty");
            transportConfig.MaximumConnections = 64;
            _transporter.Open(transportConfig);
        }

        Debug.Log("Connecting to " + remoteEndPoint);
        _initialSyncDone = false;
        _ramnet.ConnectionManager.Connect(remoteEndPoint,
                                          (connId, endpoint) => {
            OnConnectionEstablished(connId, endpoint);
            onEstablished(connId, endpoint);
        },
                                          (endpoint, exception) => {
            OnConnectionFailure(endpoint);
            onFailure(endpoint, exception);
        },
                                          connId => {
            OnDisconnected(connId);
            onDisconnected(connId);
        });
        _camera.gameObject.SetActive(true);
    }