Exemple #1
0
    public static void HandleConnect(ConnectMessage message)
    {
        switch (message.GameState)
        {
            case CurrentGameState.ResourceLoading:
                GameController.Instance.ActionsQueue.AddAction(new ObserverPlayGame());
                break;
            case CurrentGameState.WaitingForGame:
                LoadingScreenController.Instance.IsPressed = true;
                GameController.Instance.ActionsQueue.AddAction(new ObserverPlayGame());
                break;
            case CurrentGameState.ActiveGame:
                ObserverData.GameActive = true;
                LoadingScreenController.Instance.IsPressed = true;
                BallCreator.Instance.CreateAllNextFrame = message.BallsList;

                var empty = new EmptyAction();
                empty.Start += (action)=>
                {
                    PlayerData.Points = message.PlayerInfo.Points;
                    PlayerData.Health = message.PlayerInfo.Health;
                    PlayerData.LevelTimer = message.PlayerInfo.Timer;
                    PlayerData.Level = message.PlayerInfo.Level;
                };
                GameController.Instance.ActionsQueue.AddAction(empty);

                break;
            case CurrentGameState.LevelUp:
                GameController.Instance.ActionsQueue.AddAction(new ObserverLevelUp());
                break;
            case CurrentGameState.EndGame:
                break;
        }
    }
Exemple #2
0
        public async Task Listen()
        {
            try
            {
                var request = await Client.ReceiveAsync();
                var requestMessage = Messaging.ReceiveMessage(request.Buffer);
                if (requestMessage.MessageId != PreviousMessageIdReceived)
                {
                    UniqueMessagesReceived++;
                    PreviousMessageIdReceived = requestMessage.MessageId;
                }
                BytesUsed += request.Buffer.Length;
                Terminal.Log($"Bytes Used: {BytesUsed}B {KilobytesUsed}KB {MegabytesUsed}MB  ", 0, true);
                Terminal.Log($"{KilobytesPerSecond} KB/s  ", 0, ConsoleColor.Cyan);
                Terminal.Log($"Recv: {UniqueMessagesReceived}  ", 0, ConsoleColor.Green);
                Terminal.Log($"Avg: {AverageMessageSize}KB        ", 0, ConsoleColor.Magenta);

                switch (requestMessage.Type)
                {
                    case MessageType.Connect:
                        var connectionMessage = new ConnectMessage(requestMessage.Payload);
                        var connection = new Connection(request.RemoteEndPoint, requestMessage.ConnectionId,
                            requestMessage.Channel, connectionMessage.ScreenWidth, connectionMessage.ScreenHeight);
                        if (Connections.Any(cr => cr.Id.Equals(connection.Id)))
                        {
                            Connections.Remove(Connections.First(cr => cr.Id.Equals(connection.Id)));
                        }
                        Connections.Add(connection);
                        Terminal.LogLine($"Channel {connection.Channel} received connection from client {connection.Id} ({connection.IpEndPoint})", ConsoleColor.DarkGreen);
                        var channelConnections = Connections.Where(cr => cr.Channel.Equals(connection.Channel)).ToArray();
                        if (channelConnections.Count() == 2)
                        {
                            await SendAcknowledgement(channelConnections.ElementAt(0), channelConnections.ElementAt(1));
                        }
                        break;
                    case MessageType.Disconnect:
                        Connections.RemoveAll(cr => cr.Id.Equals(requestMessage.ConnectionId));
                        Terminal.LogLine($"Client {requestMessage.ConnectionId} disconnected from channel {requestMessage.Channel}", ConsoleColor.Yellow);
                        await SendMessage(requestMessage);
                        break;
                    case MessageType.Terminate:
                        Connections.RemoveAll(cr => cr.Id.Equals(requestMessage.ConnectionId));
                        Terminal.LogLine($"Client {requestMessage.ConnectionId} terminated connection from channel {requestMessage.Channel}", ConsoleColor.Magenta);
                        await SendMessage(requestMessage);
                        break;
                    default:
                        if (!Elapsed.IsRunning) Elapsed.Start();
                        await SendMessage(requestMessage);
                        break;
                }
            }
            catch (Exception ex)
            {
                Terminal.LogLine($"Something bad happend: {ex.Message} {ex.InnerException?.Message}", ConsoleColor.Red);
            }
        }
        public static ConnectMessage Deserialize(string rawMessage)
        {
            ConnectMessage msg = new ConnectMessage();
            //  1:: [path] [query]
            //  1::/test?my=param
            msg.RawMessage = rawMessage;

            string[] args = rawMessage.Split(SPLITCHARS, 3);
            if (args.Length == 3)
            {
                string[] pq = args[2].Split(new char[] { '?' });

                if (pq.Length > 0)
                    msg.Endpoint = pq[0];

                if (pq.Length > 1)
                    msg.Query = pq[1];
            }
            return msg;
        }
Exemple #4
0
        private void ProcessConnectMessage(IMessageAdapter innerAdapter, ConnectMessage message)
        {
            if (message.Error != null)
            {
                this.AddErrorLog(LocalizedStrings.Str625Params, innerAdapter.GetType().Name, message.Error);
            }
            else
            {
                var adapter = _hearbeatAdapters[innerAdapter];

                foreach (var supportedMessage in adapter.SupportedMessages)
                {
                    _messageTypeAdapters.SafeAdd(supportedMessage).Add(adapter);
                }

                _connectedAdapters.Add(adapter);
            }

            SendOutMessage(message);
        }
        /// <summary>
        /// Called when starting tracking.
        /// </summary>
        protected override void OnStart()
        {
            TrackerMessage message;

            message = new ConnectMessage(this.transactionId);
            message = this.ExecuteUdpRequest(this.TrackerUri, message);

            if (message is ConnectResponseMessage)
            {
                if (message.TransactionId == this.transactionId)
                {
                    this.connectionId = message.As <ConnectResponseMessage>().ConnectionId;
                }
                else
                {
                    // connect failed -> drop tracker
                    Debug.WriteLine($"connecting to tracker {this.TrackerUri} failed");
                }
            }
        }
        public static UdpTrackerMessage DecodeMessage(byte[] buffer, int offset, int count, MessageType type)
        {
            UdpTrackerMessage m = null;
            var action = type == MessageType.Request ? ReadInt(buffer, offset + 8) : ReadInt(buffer, offset);
            switch (action)
            {
                case 0:
                    if (type == MessageType.Request)
                        m = new ConnectMessage();
                    else
                        m = new ConnectResponseMessage();
                    break;
                case 1:
                    if (type == MessageType.Request)
                        m = new AnnounceMessage();
                    else
                        m = new AnnounceResponseMessage();
                    break;
                case 2:
                    if (type == MessageType.Request)
                        m = new ScrapeMessage();
                    else
                        m = new ScrapeResponseMessage();
                    break;
                case 3:
                    m = new ErrorMessage();
                    break;
                default:
                    throw new ProtocolException(string.Format("Invalid udp message received: {0}", buffer[offset]));
            }

            try
            {
                m.Decode(buffer, offset, count);
            }
            catch
            {
                m = new ErrorMessage(0, "Couldn't decode the tracker response");
            }
            return m;
        }
Exemple #7
0
        void HandleConnectMessage(ConnectMessage m)
        {
            var channel = Channels.SingleOrDefault(ch => ch.Id == m.Channel);

            if (channel == null)
            {
                return;
            }
            channel.Messages.Add(m);

            if (Users.SingleOrDefault(u => u.Name == m.Sender) == null)
            {
                Users.Add(new User {
                    Name = m.Sender
                });
            }
            if (channel == Channels.First())
            {
                _messenger.SendAsync(new StatusMessage(m.Sender, Status.Online));
            }
        }
Exemple #8
0
        public ConnectionState Connect(string username, string password = "")
        {
            ConnectionState = ConnectionState.Connecting;
            conn.Connect(Server, Port);

            var msg = new ConnectMessage();

            msg.ClientId     = ClientId;
            msg.CleanSession = CleanSession;
            if (!string.IsNullOrEmpty(username))
            {
                msg.UsernameFlag = true;
                msg.Username     = username;
            }
            if (!string.IsNullOrEmpty(password))
            {
                msg.PasswordFlag = true;
                msg.Password     = password;
            }
            msg.KeepAlive = KeepAlive;
            conn.SendMessage(msg);

            if (!connResetEvent.WaitOne(5000, false))
            {
                ConnectionState = ConnectionState.Disconnecting;
                Dispose();
                ConnectionState = ConnectionState.Disconnected;
                return(ConnectionState);
            }

            if (ConnectionState == ConnectionState.Connected)
            {
                pingTimer = new Timer((state) =>
                {
                    conn.SendMessage(new PingReqMessage());
                }, null, KeepAlive * 1000, KeepAlive * 1000);
            }

            return(ConnectionState);
        }
Exemple #9
0
 public void Connect(IPEndPoint endPoint)
 {
     if (!_tcpClient.Connected)
     {
         try
         {
             _tcpClient.Connect(endPoint);
             _stream = _tcpClient.GetStream();
             NetworkHelper.SendSingleMessage(_tcpClient, new ConnectMessage(_networkManager.username), new PlayerInfo(ClientId, _networkManager.username));
             NetworkMessage message = NetworkHelper.ReceiveSingleMessage(_tcpClient);
             if (message is ConnectMessage)
             {
                 ConnectMessage connectMessage = (ConnectMessage)message;
                 this.ClientId    = connectMessage.playerInfo.userId;
                 this._playerInfo = connectMessage.playerInfo;
                 _logger.Debug("Received client id: " + ClientId);
                 _stream.BeginRead(_headerBuffer, 0, _headerBuffer.Length, ReadHeader, null);
                 // Notify callbacks that we're connected
                 _listeners.ForEach(listener => listener?.OnConnected());
             }
             else
             {
                 _tcpClient.Close();
                 _listeners.ForEach(listener => listener?.OnDisconnected());
                 throw new Exception("Client expected ConnectMessage, but received: " + message.GetType());
             }
         }
         catch (Exception e)
         {
             _logger.Debug(e);
             if (_networkManager.IsServer)
             {
                 _networkManager.StopServer();
             }
             _listeners.ForEach(listener => listener?.OnDisconnected());
             throw new Exception("Could not connect to the server!");
         }
     }
 }
Exemple #10
0
        private void OnConnectQueryMessageRsp(IMessage msg, NetConnection conn)
        {
            var rspMsg = (QueryConnectMessageRsp)msg;

            if (rspMsg.ConnectionType == QueryConnectMessageRsp.ClientType)
            {
                client.DisConnect();
            }
            else
            {
                string name    = "TestClientName";
                string ip      = "127.0.0.1";
                string info    = "ext info";
                var    connMsg = new ConnectMessage()
                {
                    Address     = ip,
                    ConnectName = name,
                    Information = info,
                };
                client.SendMessage(connMsg);
            }
        }
Exemple #11
0
    // Start is called before the first frame update
    void Start()
    {
        newPlayers          = new List <string>();
        droppedPlayers      = new List <string>();
        currentPlayers      = new Dictionary <string, GameObject>();
        initialSetofPlayers = new ListOfPlayers();

        udp = new UdpClient();
        udp.Connect("54.152.99.54", 12345);

        ConnectMessage msg = new ConnectMessage();

        msg.cmd = "connect";
        Byte[] sendBytes = Encoding.ASCII.GetBytes(JsonUtility.ToJson(msg));
        udp.Send(sendBytes, sendBytes.Length);
        udp.BeginReceive(new AsyncCallback(OnReceived), udp);



        InvokeRepeating("HeartBeat", 1, 1);
        InvokeRepeating("Position", 0.5f, 0.5f);
    }
Exemple #12
0
        void ReconnectToService()
        {
            //if (m_connected)
            //    m_duplexClient.SendToServiceAsync(new DisconnectMessage());

            ConnectMessage msg = new ConnectMessage();

            msg.NodeID = ((App)Application.Current).NodeValue;
            msg.TimeSeriesDataRootUrl    = ((App)Application.Current).TimeSeriesDataServiceUrl; // "http://localhost:6152/historian/timeseriesdata/read/";
            msg.RealTimeStatisticRootUrl = ((App)Application.Current).RealTimeStatisticServiceUrl;
            msg.CurrentDisplayType       = DisplayType.Home;
            if (ComboBoxMeasurements.Items.Count > 0)
            {
                msg.DataPointID   = ((Measurement)ComboBoxMeasurements.SelectedItem).PointID;
                m_framesPerSecond = (int)((Measurement)ComboBoxMeasurements.SelectedItem).FramesPerSecond;
                LinearAxis yAxis = (LinearAxis)ChartRealTimeData.Axes[1];
                if (((Measurement)ComboBoxMeasurements.SelectedItem).SignalSuffix == "PA")
                {
                    yAxis.Minimum  = -180;
                    yAxis.Maximum  = 180;
                    yAxis.Interval = 60;
                }
                else
                {
                    yAxis.Minimum  = 59.95;
                    yAxis.Maximum  = 60.05;
                    yAxis.Interval = 0.02;
                }
            }
            else
            {
                msg.DataPointID = 0;
            }

            SendToService(msg);

            //reset time series data list
            timeSeriesDataList = new ObservableCollection <TimeSeriesDataPoint>();
        }
Exemple #13
0
        private void OnConnectQueryMessageRsp(IMessage msg, NetConnection conn)
        {
            var queryMsg = (QueryConnectMessageRsp)msg;

            if (queryMsg.ConnectionType != QueryConnectMessageRsp.ServerType)
            {
                var disMsg = new DisconnectMessage();
                server.SendMessage(disMsg, conn);
            }
            else
            {
                string name    = "TestServerName";
                string ip      = "127.0.0.1";
                string info    = "ext info";
                var    connMsg = new ConnectMessage()
                {
                    Address     = ip,
                    ConnectName = name,
                    Information = info,
                };
                server.SendMessage(connMsg, conn);
            }
        }
Exemple #14
0
        public DataSource()
        {
            TimeSpan throttle = TimeSpan.FromMilliseconds(1);

            string RegistryConnectionString = "akka.tcp://ReceiverActorSystem@" + serverURL + ":" + serverPort + "/user/DataReceiverActor";

            ColourConsole.WriteLineMagenta("Sending ConnectMessage");
            ConnectMessage requestAccess = Context.ActorSelection(RegistryConnectionString).Ask <ConnectMessage>(new ConnectMessage(Self)).Result;//Changes

            DataReceiverActorRef = requestAccess.ActorRef;

            Receive <RequestLogs>(request =>
            {
                ColourConsole.WriteLineMagenta("Sending RequestLogs");
                // create a source
                StreamLogs(request.StreamId)
                //Throttle outbound stream
                .Throttle(1, throttle, 1, ThrottleMode.Shaping)
                // materialize it using stream refs
                .RunWith(StreamRefs.SourceRef <string>(), Context.System.Materializer())
                // and send to sink
                .PipeTo(DataReceiverActorRef, success: sourceRef => new LogsOffer(request.StreamId, sourceRef));    //DataReceiverActorRef was Sender
            });
        }
Exemple #15
0
        private void CacheRequest(int source, int session, string method, ClusterClientRequest request, string remoteNode)
        {
            string ipEndpoint = m_clusterConfig[remoteNode].ToString();
            Queue <WaitForSendRequest> waittingQueue = null;
            bool isExist = m_waitForSendRequests.TryGetValue(ipEndpoint, out waittingQueue);

            if (!isExist)
            {
                waittingQueue = new Queue <WaitForSendRequest>();
                m_waitForSendRequests.Add(ipEndpoint, waittingQueue);
            }

            if (waittingQueue.Count <= 0)
            {
                string[] ipResult   = ipEndpoint.Split(':');
                string   remoteIp   = ipResult[0];
                int      remotePort = Int32.Parse(ipResult[1]);

                ConnectMessage connectMessage = new ConnectMessage();
                connectMessage.IP          = remoteIp;
                connectMessage.Port        = remotePort;
                connectMessage.TcpObjectId = m_tcpObjectId;
                connectMessage.Type        = SocketMessageType.Connect;

                NetworkPacketQueue.GetInstance().Push(connectMessage);
            }

            WaitForSendRequest waitRequest = new WaitForSendRequest();

            waitRequest.Source  = source;
            waitRequest.Session = session;
            waitRequest.Method  = method;
            waitRequest.Request = request;

            waittingQueue.Enqueue(waitRequest);
        }
        public override async Task <MqttMessage> ProcessAsync()
        {
            if (Session.IsConnected)
            {
                Session.Disconnect(Message);
                return(null);
            }

            ConnectMessage msg = Message as ConnectMessage;

            //wrong protocol version
            if (msg.ProtocolVersion != 4)
            {
                Session.ConnectResult = ConnectAckCode.UnacceptableProtocolVersion;
                return(await Task.FromResult <MqttMessage>(new ConnectAckMessage(false, ConnectAckCode.UnacceptableProtocolVersion)));
            }

            //0-byte client id and clean session = 0
            if (msg.ClientId == null && !msg.CleanSession)
            {
                Session.ConnectResult = ConnectAckCode.IdentifierRejected;
                return(await Task.FromResult <MqttMessage>(new ConnectAckMessage(false, ConnectAckCode.IdentifierRejected)));
            }

            if (!Session.IsAuthenticated)
            {
                Session.ConnectResult = ConnectAckCode.NotAuthorized;
                return(await Task.FromResult <MqttMessage>(new ConnectAckMessage(false, ConnectAckCode.BadUsernameOrPassword)));
            }
            else
            {
                Session.IsConnected = true;
                Session.Connect(ConnectAckCode.ConnectionAccepted);
                return(await Task.FromResult <MqttMessage>(new ConnectAckMessage(false, ConnectAckCode.ConnectionAccepted)));
            }
        }
Exemple #17
0
        //Recieves the next available Message
        protected Message RecieveMessage(out IPEndPoint sender)
        {
            var bytes = FetchMessage(out sender);

            if (bytes.Length == 0)
            {
                return(new Message()); //Error message
            }
            var     msgType = (MessageType)bytes[0];
            Message msg;

            switch (msgType)
            {
            case MessageType.Connect:
                msg = new ConnectMessage();
                break;

            case MessageType.Disconnect:
                msg = new Message();
                break;

            case MessageType.Data:
                msg = new Message();
                break;

            case MessageType.Error:
                msg = new Message();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            msg.Read(bytes);
            return(msg);
        }
Exemple #18
0
 void OnConnected(NetworkConnection conn, ConnectMessage message)
 {
     Debug.Log("Client connected");
 }
Exemple #19
0
 public static string GetString(ConnectMessage connectMessage) => Serialize(connectMessage);
 void OnServerConnect(NetworkConnection nc, ConnectMessage cm)
 {
     //*Debug.Log("New client connected: " + nc);
 }
 void OnClientConnect(NetworkConnection nc, ConnectMessage cm)
 {
     //*Debug.Log("Connected to server: " + nc);
 }
        private void OnConnectionChanged(Codes code, Exception error, string text)
        {
            try
            {
                Message message;

                if (error == null)
                {
                    switch (code)
                    {
                    case Codes.DllConnected:
                    case Codes.QuikConnected:
                        try
                        {
                            bool isAlive;

                            try
                            {
                                isAlive = IsConnectionAlive();
                            }
                            catch
                            {
                                isAlive = false;
                            }

                            GetTerminal().AssignProcess();

                            message = new ConnectMessage
                            {
                                Error = isAlive ? null : new ApiException(code, LocalizedStrings.Str1837)
                            };
                        }
                        catch (Exception ex)
                        {
                            message = new ConnectMessage {
                                Error = ex
                            };
                        }
                        break;

                    case Codes.DllDisconnected:
                        message = new DisconnectMessage();
                        break;

                    case Codes.QuikDisconnected:
                        message = new ConnectMessage {
                            Error = new ApiException(code, text)
                        };
                        break;

                    default:
                        message = new ConnectMessage
                        {
                            Error = new InvalidOperationException(LocalizedStrings.Str1838Params.Put(code))
                        };
                        break;
                    }
                }
                else
                {
                    message = new ConnectMessage {
                        Error = error
                    };
                }

                SendOutMessage(message);
            }
            catch (Exception ex)
            {
                SendOutError(ex);
            }
        }
Exemple #23
0
        //device本身不会直接收到connect消息,一个socket都是处理完connect消息,才和Device建立关联。
        internal void OnConnectMessageReceived(IChannel channel, ConnectMessage cm)
        {
            var sessionCode = cm.SessionCode;

            //对方发了一个SessionCode,表示以前可能连接过?
            if (!string.IsNullOrEmpty(sessionCode))
            {
                if (Crypto != null)
                {
                    sessionCode = Crypto.Decrypt(sessionCode);
                }

                //确实连接过。而且还没过期。自动同意这个设备。
                if (sessionCode == SessionCode)
                {
                    ConnectingOutTimer?.Stop();
                    //原来的channel应该是坏掉了,不然对方为什么要发Connect消息呢?所以换成对方创建的channel.
                    IsRequester = false;
                    SwitchChannel(channel);
                    //先换channel才能成功发送Accept消息。
                    Accept();
                    return;
                }
            }

            //如果没有SessionCode或者SessionCode不等于当前SessionCode.
            //启动全新连接流程。
            if (!string.IsNullOrEmpty(cm.ChallengeString))
            {
                //对方要求加密
                cm.ExtractToDevice(this);
                //其实验证还是可以在B这一端完成。因为A可以用它自己的密码加密它的密码。如果B输入的密码和解出来的密码一致,就认为认证成功,
                //并发送Accept消息给A, 最终还是要由A确认是否进入可通讯状态。所以改成那个方案意义不太大。
                //还是要有这么个字段,因为ChallengeRequest这个字段,在ConnectingIn的事件处理中,在Accept的时候要用。
                ChallengeRequest = cm.ChallengeString;
                IsRequester      = false;
                SwitchChannel(channel);
                bool shouldAskUserInput = true;

                //对方是否知道我的ConnectCode?
                if (!string.IsNullOrEmpty(cm.ConnectCode))
                {
                    //对方发来的ConnectCode是加密的
                    //我看一下是不是用我的密码加密的?我能判断是因为EncedConnectCode的原值就是ConnectCode(原始内容其实并不一定是ConnectCode,现在用了,只是为了方便)。
                    var ld = AppModel.Instance.LocalDevice;

                    string connectCode = null;
                    using (var sp = new SecurePassword(ld.ConnectCode))
                        using (var crypto = Env.Instance.SecurityManager.CreateCrypto(sp))
                        {
                            connectCode = crypto.Decrypt(cm.ConnectCode);
                        }

                    if (connectCode != null &&
                        connectCode == ld.ConnectCode)
                    {
                        if (Env.Instance.Config.PairedDevice != null &&
                            Env.Instance.Config.PairedDevice.ID != ID)
                        {
                            Reject(RejectMessage.ALLOW_ONLY_ONE_PAIR_DEVICE);
                        }
                        //对方知道ChannelCode,并正确的用这个ChannelCode给它自己的ID加了密。
                        ChannelCode = new SecurePassword(connectCode);
                        Accept();
                        Env.Instance.Config.PairedDevice = this;
                        Env.Instance.Config.Save();
                        shouldAskUserInput = false;
                    }
                    else
                    {
                        Reject(RejectMessage.CONNECT_CODE_INCORRECT);
                        return;
                    }
                }

                if (shouldAskUserInput)
                {
                    State = DeviceState.ConnectingIn;
                }
                return;
            }
            else
            {
                //对方不要求加密。
                this.ChallengeRequest = null;
                if (State == DeviceState.ConnectingOut)
                {
                    //如果是我去连接别人了,别人同时,或者稍后,给我发了ConnectMessage。
                    cm.ExtractToDevice(this);
                    TryAutoAccept(channel);
                }
                else if (State == DeviceState.ConnectingIn)
                {
                    //如果刚刚已经连接进来,并等待批准,为什么还要再连接?
                }
                else
                {
                    //可能是通过广播搜到的,也可能是别人拍了我的二维码主动连过来的,现在开始发起实际连接了,从前没有成功连接过。
                    cm.ExtractToDevice(this);//如果没有发现别人,别人直接连过来了,这个动作做了两次。没办法。本来在这里做最合适。但那里要汇报deviceDiscovered。
                    IsRequester = false;
                    SwitchChannel(channel);

                    var app    = AppModel.Instance;
                    var config = Env.Instance.Config;
                    //如果这个设备在信任设备列表中。
                    if (!string.IsNullOrEmpty(cm.ConnectCode) && cm.ConnectCode == app.LocalDevice.ConnectCode)
                    {
                        //如果这个设备所代表的对方发送了一个ConnectCode,而且这个ConnectCode与本机的ConnectCode一致,说明对方知道我的口令,自动同意连接。而且添加为信任设备
                        //TODO bug 这样还不够,应该从AppModel里面去取Device,然后再add或者replace,让所有的地方都只保留一个Device的引用。

                        //不过Device这个类应该是保证了它一定是AppModel里面的。因为在Connect之前已经检查了。
                        config.TrustDevices.AddOrReplace(this);
                        config.Save();
                    }

                    //如果上面成功添加了可信设备,这里就会自动接受了。
                    if (config.TrustDevices.FirstOrDefault(d => d.ID == this.ID) != null)
                    {
                        Accept();
                    }
                    else
                    {
                        //这会触发ConnectingIn事件,用户可以决定是否同意这个连接。
                        State = DeviceState.ConnectingIn;
                    }
                }
            }
        }
 void OnServerConnect(NetworkConnection conn, ConnectMessage msg)
 {
     Debug.Log("New client connected: " + conn);
 }
 void ReconnectToService()
 {
     ConnectMessage msg = new ConnectMessage();
     msg.NodeID = ((App)Application.Current).NodeValue;
     msg.TimeSeriesDataRootUrl = ((App)Application.Current).TimeSeriesDataServiceUrl;	// "http://localhost:6152/historian/timeseriesdata/read/";
     msg.RealTimeStatisticRootUrl = ((App)Application.Current).RealTimeStatisticServiceUrl;
     msg.CurrentDisplayType = DisplayType.ServiceClient;
     msg.DataPointID = 0;
     m_duplexClient.SendToServiceAsync(msg);
 }
Exemple #26
0
 /// <summary>Called on the server when a client connects</summary>
 /// <remarks>
 /// We store some stuff here so that things can be cleaned up when the client disconnects.
 /// </remarks>
 /// <param name="message"></param>
 static private void OnServerConnect(NetworkConnection conn, ConnectMessage message)
 {
     OnServerConnect(conn);
 }
        void ReconnectToService()
        {
            //if (m_connected)
            //    m_duplexClient.SendToServiceAsync(new DisconnectMessage());

            ConnectMessage msg = new ConnectMessage();
            msg.NodeID = ((App)Application.Current).NodeValue;
            msg.TimeSeriesDataRootUrl = ((App)Application.Current).TimeSeriesDataServiceUrl;	// "http://localhost:6152/historian/timeseriesdata/read/";
            msg.RealTimeStatisticRootUrl = ((App)Application.Current).RealTimeStatisticServiceUrl;
            msg.CurrentDisplayType = DisplayType.Home;
            if (ComboBoxMeasurements.Items.Count > 0)
            {
                msg.DataPointID = ((Measurement)ComboBoxMeasurements.SelectedItem).PointID;
                m_framesPerSecond = (int)((Measurement)ComboBoxMeasurements.SelectedItem).FramesPerSecond;
                LinearAxis yAxis = (LinearAxis)ChartRealTimeData.Axes[1];
                if (((Measurement)ComboBoxMeasurements.SelectedItem).SignalSuffix == "PA")
                {
                    yAxis.Minimum = -180;
                    yAxis.Maximum = 180;
                    yAxis.Interval = 60;
                }
                else
                {
                    yAxis.Minimum = 59.95;
                    yAxis.Maximum = 60.05;
                    yAxis.Interval = 0.02;
                }
            }
            else
                msg.DataPointID = 0;

            SendToService(msg);

            //reset time series data list
            timeSeriesDataList = new ObservableCollection<TimeSeriesDataPoint>();
        }
 public EventMessageConnectArgs(ConnectMessage connectMessage)
 {
     ConnectMessage = connectMessage;
 }
Exemple #29
0
        private void mqttClient_Connected(object sender, MqttClientConnectedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_options.ScadaId) == false)
                {
                    string scadaCmdTopic  = string.Format("iot-2/evt/wacmd/fmt/{0}", _options.ScadaId);
                    string deviceCmdTopic = string.Format("iot-2/evt/wacmd/fmt/{0}/{1}", _options.ScadaId, _options.ScadaId);

                    _configTopic    = string.Format("iot-2/evt/wacfg/fmt/{0}", _options.ScadaId);
                    _dataTopic      = string.Format("iot-2/evt/wadata/fmt/{0}", _options.ScadaId);
                    _scadaConnTopic = string.Format("iot-2/evt/waconn/fmt/{0}", _options.ScadaId);
                    //  kelly
                    _deviceConnTopic = string.Format("iot-2/evt/waconn/fmt/{0}", _options.ScadaId);
                    //
                    _actcTopic = string.Format("iot-2/evt/waactc/fmt/{0}/{1}", _options.ScadaId, _options.ScadaId);
                    _actdTopic = string.Format("iot-2/evt/waactd/fmt/{0}/{1}", _options.ScadaId, _options.ScadaId);

                    _stTopic = string.Format("iot-2/evt/wast/fmt/{0}", _options.ScadaId);

                    if (_options.Type == EdgeType.Gateway)
                    {
                        _cmdTopic = scadaCmdTopic;
                    }
                    else
                    {
                        _cmdTopic = deviceCmdTopic;
                    }
                }

                if (_options.Heartbeat > 0)
                {
                    if (_heartbeatTimer == null)
                    {
                        _heartbeatTimer = new Timer();
                    }

                    _heartbeatTimer.Enabled  = false;
                    _heartbeatTimer.Interval = _options.Heartbeat;
                }

                if (Connected != null)
                {
                    Connected(this, new EdgeAgentConnectedEventArgs(e.IsSessionPresent));
                }

                // subscribe
                _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(_cmdTopic).WithAtLeastOnceQoS().Build());
                //_mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(_actdTopic).WithAtLeastOnceQoS().Build());
                _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(_actcTopic).WithAtLeastOnceQoS().Build());
                _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(_stTopic).WithAtLeastOnceQoS().Build());

                // publish
                ConnectMessage connectMsg = new ConnectMessage();
                connectMsg.ScadaList = new Dictionary <string, ConnectMessage.DObject>();
                ConnectMessage.DObject scada = new ConnectMessage.DObject();
                connectMsg.ScadaList.Add(_options.ScadaId, scada);
                string payload = JsonConvert.SerializeObject(connectMsg);
                var    message = new MqttApplicationMessageBuilder()
                                 .WithTopic((_options.Type == EdgeType.Gateway) ? _scadaConnTopic : _deviceConnTopic)
                                 .WithPayload(payload)
                                 .WithAtLeastOnceQoS()
                                 .WithRetainFlag(true)
                                 .Build();

                _mqttClient.PublishAsync(message);

                // start heartbeat timer
                _heartbeatTimer.Enabled = true;
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }
 void ReconnectToService()
 {
     ConnectMessage msg = new ConnectMessage();
     msg.NodeID = ((App)Application.Current).NodeValue;
     msg.TimeSeriesDataRootUrl = ((App)Application.Current).TimeSeriesDataServiceUrl;
     msg.RealTimeStatisticRootUrl = ((App)Application.Current).RealTimeStatisticServiceUrl;
     msg.CurrentDisplayType = DisplayType.RealTimeStatistics;
     msg.DataPointID = 0;
     m_duplexClient.SendToServiceAsync(msg);
 }
Exemple #31
0
 public override async Task Login(IChannel channel, string deviceId, ConnectMessage mqttConnectMessage)
 {
     channel.GetAttribute(LoginAttrKey).Set("login");
     channel.GetAttribute(DeviceIdAttrKey).Set(deviceId);
     await Init(channel, mqttConnectMessage);
 }
 void OnClientConnect(NetworkConnection conn, ConnectMessage msg)
 {
     Debug.Log(Time.time + "Connected to server: " + conn);
 }
Exemple #33
0
        private async Task Init(IChannel channel, ConnectMessage mqttConnectMessage)
        {
            String deviceId = await GetDeviceId(channel);

            MqttChannel mqttChannel = new MqttChannel()
            {
                Channel         = channel,
                CleanSession    = mqttConnectMessage.CleanSession,
                ClientId        = mqttConnectMessage.ClientId,
                SessionStatus   = SessionStatus.OPEN,
                IsWill          = mqttConnectMessage.HasWill,
                SubscribeStatus = SubscribeStatus.No,
                Messages        = new ConcurrentDictionary <int, SendMqttMessage>(),
                Topics          = new List <string>()
            };

            if (Connect(deviceId, mqttChannel))
            {
                if (mqttConnectMessage.HasWill)
                {
                    if (mqttConnectMessage.WillMessage == null || string.IsNullOrEmpty(mqttConnectMessage.WillTopic))
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError($"WillMessage 和 WillTopic不能为空");
                        }
                        return;
                    }
                    var willMessage = new MqttWillMessage
                    {
                        Qos         = mqttConnectMessage.Qos,
                        WillRetain  = mqttConnectMessage.WillRetain,
                        Topic       = mqttConnectMessage.WillTopic,
                        WillMessage = Encoding.UTF8.GetString(mqttConnectMessage.WillMessage)
                    };
                    _willService.Add(mqttConnectMessage.ClientId, willMessage);
                }
                else
                {
                    _willService.Remove(mqttConnectMessage.ClientId);
                    if (!mqttConnectMessage.WillRetain && mqttConnectMessage.WillQualityOfService != 0)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError($"WillRetain 设置为false,WillQos必须设置为AtMostOnce");
                        }
                        return;
                    }
                }
                await channel.WriteAndFlushAsync(new ConnAckPacket
                {
                    ReturnCode     = ConnectReturnCode.Accepted,
                    SessionPresent = !mqttConnectMessage.CleanSession
                });

                var sessionMessages = _clientSessionService.GetMessages(mqttConnectMessage.ClientId);
                if (sessionMessages != null && !sessionMessages.IsEmpty)
                {
                    for (; sessionMessages.TryDequeue(out SessionMessage sessionMessage) && sessionMessage != null;)
                    {
                        switch (sessionMessage.QoS)
                        {
                        case 0:
                            await _messagePushService.SendQos0Msg(channel, sessionMessage.Topic, sessionMessage.Message);

                            break;

                        case 1:
                            await _messagePushService.SendQosConfirmMsg(QualityOfService.AtLeastOnce, GetMqttChannel(deviceId), sessionMessage.Topic, sessionMessage.Message);

                            break;

                        case 2:
                            await _messagePushService.SendQosConfirmMsg(QualityOfService.ExactlyOnce, GetMqttChannel(deviceId), sessionMessage.Topic, sessionMessage.Message);

                            break;
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Logins the specified channel.
 /// </summary>
 /// <param name="channel">The channel.</param>
 /// <param name="deviceId">The device identifier.</param>
 /// <param name="mqttConnectMessage">The MQTT connect message.</param>
 /// <returns>Task.</returns>
 public abstract Task Login(IChannel channel, string deviceId, ConnectMessage mqttConnectMessage);
Exemple #35
0
		private void OnConnectMessage (ConnectMessage msg)
		{
			if (!msg.Protocols.Any())
			{
				DisconnectAsync (ConnectionResult.FailedHandshake);
				return;
			}

			string signingHashAlgorithm = null;
			if (this.requiresHandshake)
			{
				bool foundHashAlg = false;
				if (this.localCrypto != null) {
					foreach (string hashAlg in this.localCrypto.SupportedHashAlgs) {
						if (msg.SignatureHashAlgorithms.Contains (hashAlg)) {
							signingHashAlgorithm = hashAlg;
							foundHashAlg = true;
							break;
						}
					}
				}

				if (!foundHashAlg)
				{
					this.provider.SendConnectionlessMessageAsync (new DisconnectMessage { Reason = ConnectionResult.IncompatibleVersion }, RemoteTarget);
					Disconnect (ConnectionResult.FailedHandshake);
					return;
				}
			}

			foreach (Protocol protocol in msg.Protocols)
			{
				Protocol lp;
				if (!this.provider.protocols.TryGetValue (protocol.id, out lp) || !lp.CompatibleWith (protocol))
				{
					this.provider.SendConnectionlessMessageAsync (new DisconnectMessage { Reason = ConnectionResult.IncompatibleVersion }, RemoteTarget);
					Disconnect (ConnectionResult.IncompatibleVersion);
					return;
				}
			}

			var protocols = this.provider.protocols.Values.Intersect (msg.Protocols);
			this.serializer = new ServerMessageSerializer (this, protocols);
			this.serializer.SigningHashAlgorithm = signingHashAlgorithm;
			this.receivedProtocols = true;

			if (!this.requiresHandshake)
			{
				this.formallyConnected = true;
				this.provider.Connect (this);

				SendAsync (new ConnectedMessage { ConnectionId = ConnectionId });
			}
			else
			{
				SendAsync (new AcknowledgeConnectMessage
				{
					SignatureHashAlgorithm = this.serializer.SigningHashAlgorithm,
					EnabledProtocols = Protocols,
					ConnectionId = ConnectionId,
					PublicAuthenticationKey = this.provider.PublicKey,
					PublicEncryptionKey = this.provider.PublicKey
				});
			}
		}
Exemple #36
0
        private async Task Connected(ConnectMessage connectMsg)
        {
            await Consumer.OnStreamConnected();

            Become(BecomeConnected);
        }
Exemple #37
0
    //Sends connection message with name and color, receves back starting position
    private void EstablishConnection(LaunchGame launchMessage)
    {
        //Make and connect the TCP client
        tcpClient = new TcpClient();
        stopWatch = new Stopwatch();
        byte[] type = new byte[2];

        ConnectMessage connectMessage = new ConnectMessage(launchMessage.playerColor, launchMessage.playerName); //TODO: Send user entered color not placeholder
        var            msgBytes       = connectMessage.GetMessage();

        StartGame startMessage;

        try
        {
            tcpClient.Connect(launchMessage.serverIP, launchMessage.serverPort);
            var tcpStream = tcpClient.GetStream();

            stopWatch.Start();

            //Sending the connection message
            tcpStream.Write(msgBytes, 0, msgBytes.Length);

            //Read the reply
            tcpStream.Read(type, 0, type.Length);

            //Get latency
            long latency = stopWatch.ElapsedMilliseconds;
            stopWatch.Reset();

            //Get type
            char typeChar = BitConverter.ToChar(type, 0);

            //Got connection response, process it
            if (typeChar == 'c')
            {
                byte[] connectResponse = new byte[20];
                byte[] shortNum        = new byte[2];
                byte[] otherSnake      = new byte[60];
                byte[] food            = new byte[12];

                tcpStream.Read(connectResponse, 0, connectResponse.Length);

                //Parse the data recved into a new start message
                startMessage = new StartGame(launchMessage.playerName, launchMessage.playerColor, connectResponse, latency);

                //Get number of other clients

                tcpStream.Read(shortNum, 0, shortNum.Length);

                short numClients = BitConverter.ToInt16(shortNum, 0);

                //Read in data for each of the other snakes listed
                for (int i = 0; i < numClients; i++)
                {
                    tcpStream.Read(otherSnake, 0, otherSnake.Length);
                    startMessage.otherSnakes.Add(new SnakeData(otherSnake));
                }

                //Get amount of food in game
                tcpStream.Read(shortNum, 0, shortNum.Length);
                short numFood = BitConverter.ToInt16(shortNum, 0);

                for (int i = 0; i < numFood; i++)
                {
                    tcpStream.Read(food, 0, food.Length);
                    startMessage.foodInGame.Add(new FoodData(food));
                }

                MessageSystem.instance.DispatchMessage(startMessage);

                //Now the syncronus set up is done put the client into non blocking mode
                tcpClient.Client.Blocking = false;
            }
            else
            {
                throw new Exception("Message other then connection reply receved"); //TODO: Probley should be some way to recover from this
            }
        }
        catch (Exception e)
        {
            UnityEngine.Debug.Log("ERROR");
            UnityEngine.Debug.Log(e.ToString());
            MessageSystem.instance.DispatchMessage(new ConnectFailed(e.ToString()));
        }
    }