Beispiel #1
0
        public Form1()
        {
            InitializeComponent();

            var coreConfig = new AVClient.Configuration
            {
                ApplicationId  = appId,
                ApplicationKey = appId,
            };

            AVClient.Initialize(coreConfig);
            AVClient.HttpLog(AppendLogs);

            var realtimeConfig = new AVRealtime.Configuration()
            {
                ApplicationId          = appId,
                ApplicationKey         = appkey,
                OfflineMessageStrategy = AVRealtime.OfflineMessageStrategy.UnreadAck,
            };

            Websockets.Net.WebsocketConnection.Link();
            AVRealtime.WebSocketLog(AppendLogs);

            realtime = new AVRealtime(realtimeConfig);

            lbx_messages.DisplayMember = "Content";
            lbx_messages.ValueMember   = "Id";
            lbx_messages.DataSource    = data;

            realtime.OnOfflineMessageReceived += Realtime_OnOfflineMessageReceived;
        }
Beispiel #2
0
        public LeanCloudRealtimeHelper(string appId, string appKey, string clientId)
        {
            AVClient.Initialize(appId, appKey);
            realtime = new AVRealtime(appId, appKey);

            AVRealtime.WebSocketLog(Console.Write);
        }
Beispiel #3
0
        public static async Task Main(string[] args)
        {
            string appId    = "uay57kigwe0b6f5n0e1d4z4xhydsml3dor24bzwvzr57wdap";
            string appKey   = "kfgz7jjfsk55r5a8a3y4ttd3je1ko11bkibcikonk32oozww";
            string clientId = "wujun";

            AVClient.Initialize(appId, appKey);
            AVRealtime realtime = new AVRealtime(appId, appKey);

            AVRealtime.WebSocketLog(Console.WriteLine);


            AVIMClient tom = await realtime.CreateClientAsync(clientId, tag : "Mobile", deviceId : "xxxbbbxxx");

            tom.OnSessionClosed += Tom_OnSessionClosed;
            var conversation = await tom.GetConversationAsync("5b83a01a5b90c830ff80aea4");

            var messages = await conversation.QueryMessageAsync(limit : 10);

            var afterMessages = await conversation.QueryMessageAfterAsync(messages.First());

            var earliestMessages = await conversation.QueryMessageFromOldToNewAsync();

            var nextPageMessages = await conversation.QueryMessageAfterAsync(earliestMessages.Last());

            var earliestMessage = await conversation.QueryMessageFromOldToNewAsync(limit : 1);

            var latestMessage = await conversation.QueryMessageAsync(limit : 1);

            var messagesInInterval = await conversation.QueryMessageInIntervalAsync(earliestMessage.FirstOrDefault(), latestMessage.FirstOrDefault());

            Console.ReadKey();
        }
Beispiel #4
0
        static async void Test()
        {
            //string appId = "Eohx7L4EMfe4xmairXeT7q1w-gzGzoHsz";
            //string appKey = "GSBSGpYH9FsRdCss8TGQed0F";

            string appId  = "FQr8l8LLvdxIwhMHN77sNluX-9Nh9j0Va";
            string appKey = "MJSm46Uu6LjF5eNmqfbuUmt6";

            AVRealtime.WebSocketLog(Console.WriteLine);
            AVClient.HttpLog(Console.WriteLine);

            AVClient.Initialize(appId, appKey);
            Websockets.Net.WebsocketConnection.Link();
            var realtime = new AVRealtime(new AVRealtime.Configuration {
                ApplicationId  = appId,
                ApplicationKey = appKey
            });

            AVLiveQuery.Channel = realtime;

            var query = new AVQuery <AVObject>("GameObject").WhereEqualTo("objectId", "5cedee8e58cf480008de9caa");

            //var query = new AVQuery<AVObject>("GameObject").WhereExists("objectId");
            liveQuery = await query.SubscribeAsync();

            liveQuery.OnLiveQueryReceived += OnLiveQueryReceived;

            Console.WriteLine("done");
        }
 protected TestBase()
 {
     AVClient.HttpLog(Console.WriteLine);
     AVRealtime.WebSocketLog(Console.WriteLine);
     AVClient.Initialize(AppId, AppKey);
     CNRealtime = new AVRealtime(AppId, AppKey);
 }
Beispiel #6
0
        public virtual void SetUp()
        {
            string appId  = "cfpwdlo41ujzbozw8iazd8ascbpoirt2q01c4adsrlntpvxr";
            string appkey = "lmar9d608v4qi8rvc53zqir106h0j6nnyms7brs9m082lnl7";

            //string appId = "EB23wEzd6WPhGlwjMVgEPxg6-gzGzoHsz";
            //string appkey = "6jEGd98CIOUyH6LQrotQSNVb";

            Websockets.Net.WebsocketConnection.Link();

            var coreConfig = new AVClient.Configuration
            {
                ApplicationId  = appId,
                ApplicationKey = appId,
            };

            AVClient.Initialize(coreConfig);
            AVClient.HttpLog(AppendLogs);

            var realtimeConfig = new AVRealtime.Configuration()
            {
                ApplicationId          = appId,
                ApplicationKey         = appkey,
                RealtimeServer         = new Uri("wss://rtm51.leancloud.cn"),
                OfflineMessageStrategy = AVRealtime.OfflineMessageStrategy.Default
            };

            AVRealtime.WebSocketLog(AppendLogs);

            realtime = new AVRealtime(realtimeConfig);
        }
Beispiel #7
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //初始化登录用户信息
            usernameheader.Text = AVUser.CurrentUser.Username[0].ToString();
            username.Text       = AVUser.CurrentUser.Username;
            useremail.Text      = AVUser.CurrentUser.Email;
            //初始化即时通讯服务
            try
            {
                Websockets.Net.WebsocketConnection.Link();
                Realtime = new AVRealtime(new AVRealtime.Configuration
                {
                    ApplicationId  = "EthsHELtLfXL9XBqcFfzMrPO-gzGzoHsz",
                    ApplicationKey = "xODJ808fAD8hpLHlblQhk0t1",
                    //可以有
                    RTMRouter = new Uri("https://ethshelt.lc-cn-n1-shared.com"),
                    OfflineMessageStrategy = AVRealtime.OfflineMessageStrategy.Default
                });
                //注册自定义消息
                Realtime.RegisterMessageType <NoticeMessage>();
                //注册离线消息监听
                Realtime.OnOfflineMessageReceived += OnOfflineMessageReceived;
                //登录Client
                User = await Realtime.CreateClientAsync(AVUser.CurrentUser);

                if (AVUser.CurrentUser.Get <string>("Friends") == "null")
                {
                    //如果是第一次登录给用户添加Friends的ConversationId
                    AVIMConversation Myfriends = await User.CreateConversationAsync(member : null, name : AVUser.CurrentUser.Username + "的小伙伴们", isUnique : false);

                    AVUser.CurrentUser["Friends"] = Myfriends.ConversationId;
                    await AVUser.CurrentUser.SaveAsync();
                }
                //获取FriendsConversation
                FriendsConversation = await User.GetConversationAsync(AVUser.CurrentUser.Get <string>("Friends"));

                //上线后给所有的好友发送“我上线了”的notice
                NoticeMessage notice = new NoticeMessage
                {
                    Notice = "我上线啦"
                };
                await FriendsConversation.SendMessageAsync(notice);

                //绑定listbox数据
                BindingFriendListSrouce();
                //添加好友事件监听(好友邀请事件:同意,拒绝,好友邀请反馈事件:同意)
                User.OnInvited += OnInvited;
                //被删除事件监听
                User.OnKicked += OnKicked;
                //好友操作事件监听(删除好友,好友邀请反馈事件:拒绝)==》TODO:未完成
                //User.OnMembersLeft += OnMembersLeft;
                //User.OnMembersJoined += OnMembersJoined;
                User.OnMessageReceived += OnMessageReceived;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }
Beispiel #8
0
        public void RunCommand(AVIMCommand command)
        {
            command.IDlize();
            var requestString = command.EncodeJsonString();

            AVRealtime.PrintLog("websocket=>" + requestString);
            webSocketClient.Send(requestString);
        }
Beispiel #9
0
 private void Connection_OnClosed()
 {
     AVRealtime.PrintLog("PCL websocket closed without parameters.");
     if (this.OnClosed != null)
     {
         this.OnClosed(0, "", "");
     }
 }
 private void CallOnDisconnected()
 {
     AVRealtime.PrintLog("PCL websocket closed without parameters.");
     if (OnClosed != null)
     {
         RunInTask(() => this.OnClosed(0, "", ""));
     }
 }
Beispiel #11
0
 private void OnClose(object sender, CloseEventArgs e)
 {
     AVRealtime.PrintLog("Unity websocket closed without parameters.");
     if (this.OnClosed != null)
     {
         this.OnClosed(e.Code, e.Reason, "");
     }
 }
Beispiel #12
0
 public static void Main(string[] args)
 {
     Console.WriteLine("Hello World!");
     AVRealtime.WebSocketLog(Console.WriteLine);
     Websockets.Net.WebsocketConnection.Link();
     Test();
     Console.ReadKey(true);
 }
 // Use this for initialization
 void Start()
 {
     _instance = this;
     // 使用 AppId 和 App Key 初始化 SDK
     _avRealtime = new AVRealtime(AppId, AppKey);
     // 方便调试将 WebSocket 日志打印在 Debug.Log 控制台上
     AVRealtime.WebSocketLog(Debug.LogWarning);
 }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="command"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <Tuple <int, IDictionary <string, object> > > RunCommandAsync(AVIMCommand command, CancellationToken cancellationToken = default(CancellationToken))
        {
            var tcs = new TaskCompletionSource <Tuple <int, IDictionary <string, object> > >();

            command.IDlize();

            var requestString = command.EncodeJsonString();

            if (!command.IsValid)
            {
                requestString = "{}";
            }
            AVRealtime.PrintLog("websocket=>" + requestString);
            webSocketClient.Send(requestString);
            var requestJson = command.Encode();


            Action <string> onMessage = null;

            onMessage = (response) =>
            {
                //AVRealtime.PrintLog("response<=" + response);
                var responseJson = Json.Parse(response) as IDictionary <string, object>;
                if (responseJson.Keys.Contains("i"))
                {
                    if (requestJson["i"].ToString() == responseJson["i"].ToString())
                    {
                        var result = new Tuple <int, IDictionary <string, object> >(-1, responseJson);
                        if (responseJson.Keys.Contains("code"))
                        {
                            var errorCode = int.Parse(responseJson["code"].ToString());
                            var reason    = string.Empty;
                            int appCode   = 0;

                            if (responseJson.Keys.Contains("reason"))
                            {
                                reason = responseJson["reason"].ToString();
                            }
                            if (responseJson.Keys.Contains("appCode"))
                            {
                                appCode = int.Parse(responseJson["appCode"].ToString());
                            }
                            tcs.SetException(new AVIMException(errorCode, appCode, reason, null));
                        }
                        if (tcs.Task.Exception == null)
                        {
                            tcs.SetResult(result);
                        }
                        webSocketClient.OnMessage -= onMessage;
                    }
                    else
                    {
                    }
                }
            };
            webSocketClient.OnMessage += onMessage;
            return(tcs.Task);
        }
Beispiel #15
0
        public override void OnExecute(CommandLineApplication app, IConsole console)
        {
            AVRealtime.WebSocketLog((str) =>
            {
                console.WriteLine(str);
            });

            console.WriteLine("app inited.");
        }
Beispiel #16
0
        public void initApp()
        {
            Websockets.Net.WebsocketConnection.Link();
            string appId  = ConfigurationManager.AppSettings["appId"];
            string appKey = ConfigurationManager.AppSettings["appKey"];

            avRealtime = new AVRealtime(appId, appKey);
            //avRealtime = new AVRealtime("5ptNj5fF9TplwYYNYo34Ujmi-gzGzoHsz", "oxEMyVyz3XmlI8URg87Xp1l5");

            AVClient.HttpLog(Console.WriteLine);
        }
Beispiel #17
0
        public Task <bool> Connect(string url, string protocol = null)
        {
            var             tcs     = new TaskCompletionSource <bool>();
            Action          onOpen  = null;
            Action          onClose = null;
            Action <string> onError = null;

            onOpen = () => {
                AVRealtime.PrintLog("PCL websocket opened");
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                // 注册事件
                connection.OnMessage += Connection_OnMessage;
                connection.OnClosed  += Connection_OnClosed;
                connection.OnError   += Connection_OnError;
                tcs.SetResult(true);
            };
            onClose = () => {
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                tcs.SetException(new Exception("连接关闭"));
            };
            onError = (err) => {
                AVRealtime.PrintLog(string.Format("连接错误:{0}", err));
                connection.OnOpened -= onOpen;
                connection.OnClosed -= onClose;
                connection.OnError  -= onError;
                try {
                    connection.Close();
                } catch (Exception e) {
                    AVRealtime.PrintLog(string.Format("关闭错误的 WebSocket 异常:{0}", e.Message));
                } finally {
                    tcs.SetException(new Exception(string.Format("连接错误:{0}", err)));
                }
            };

            // 在每次打开时,重新创建 WebSocket 对象
            connection           = WebSocketFactory.Create();
            connection.OnOpened += onOpen;
            connection.OnClosed += onClose;
            connection.OnError  += onError;
            //
            if (!string.IsNullOrEmpty(protocol))
            {
                url = string.Format("{0}?subprotocol={1}", url, protocol);
            }
            connection.Open(url, protocol);
            return(tcs.Task);
        }
        public Task <bool> Connect(string url, string protocol = null)
        {
            var          tcs    = new TaskCompletionSource <bool>();
            EventHandler onOpen = null;
            EventHandler <CloseEventArgs> onClose = null;
            EventHandler <ErrorEventArgs> onError = null;

            onOpen = (sender, e) => {
                AVRealtime.PrintLog("PCL websocket opened");
                ws.OnOpen  -= onOpen;
                ws.OnClose -= onClose;
                ws.OnError -= onError;
                // 注册事件
                ws.OnMessage += OnWebSokectMessage;
                ws.OnClose   += OnClose;
                ws.OnError   += OnWebSocketError;
                tcs.SetResult(true);
            };
            onClose = (sender, e) => {
                ws.OnOpen  -= onOpen;
                ws.OnClose -= onClose;
                ws.OnError -= onError;
                tcs.SetException(new Exception("连接关闭"));
            };
            onError = (sender, e) => {
                AVRealtime.PrintLog(string.Format("连接错误:{0}", e.Message));
                ws.OnOpen  -= onOpen;
                ws.OnClose -= onClose;
                ws.OnError -= onError;
                try {
                    ws.Close();
                } catch (Exception ex) {
                    AVRealtime.PrintLog(string.Format("关闭错误的 WebSocket 异常:{0}", ex.Message));
                } finally {
                    tcs.SetException(new Exception(string.Format("连接错误:{0}", e.Message)));
                }
            };

            // 在每次打开时,重新创建 WebSocket 对象
            if (!string.IsNullOrEmpty(protocol))
            {
                url = string.Format("{0}?subprotocol={1}", url, protocol);
            }
            ws          = new WebSocket(url);
            ws.OnOpen  += onOpen;
            ws.OnClose += onClose;
            ws.OnError += onError;
            ws.ConnectAsync();
            return(tcs.Task);
        }
Beispiel #19
0
        public void SetUp()
        {
            AVRealtime.WebSocketLog(Console.WriteLine);
            AVClient.HttpLog(Console.WriteLine);

            AVClient.Initialize(AppId, AppKey, Server);
            Websockets.Net.WebsocketConnection.Link();
            var realtime = new AVRealtime(new AVRealtime.Configuration {
                ApplicationId  = AppId,
                ApplicationKey = AppKey
            });

            AVLiveQuery.Channel = realtime;
        }
        public async Task OnExecuteAsync(CommandLineApplication app, IConsole console)
        {
            AVClient.Initialize(AppId, AppKey);
            AVRealtime.WebSocketLog((str) =>
            {
                console.WriteLine(str);
            });
            AVRealtime realtime = new AVRealtime(AppId, AppKey);

            AVIMClient client = await realtime.CreateClientAsync(ClientId);

            client.OnMessageReceived += Client_OnMessageReceived;
            new RealtimeCommand().OnExecute(app, console);
        }
Beispiel #21
0
 public void Close()
 {
     if (connection != null)
     {
         connection.OnOpened  -= Connection_OnOpened;
         connection.OnMessage -= Connection_OnMessage;
         connection.OnClosed  -= Connection_OnClosed;
         connection.OnError   -= Connection_OnError;
         try {
             connection.Close();
         } catch (Exception e) {
             AVRealtime.PrintLog(string.Format("close websocket error: {0}", e.Message));
         }
     }
 }
Beispiel #22
0
    // Use this for initialization
    void Start()
    {
        var sc     = GameObject.FindObjectOfType <MyWebSocketClient>();
        var config = new AVRealtime.Configuration()
        {
            ApplicationId   = "uay57kigwe0b6f5n0e1d4z4xhydsml3dor24bzwvzr57wdap",
            ApplicationKey  = "kfgz7jjfsk55r5a8a3y4ttd3je1ko11bkibcikonk32oozww",
            WebSocketClient = sc // 使用已经初始化的 WebSocketClient 实例作为 AVRealtime 初始化的配置参数
        };

        AVRealtime.WebSocketLog(UnityEngine.Debug.Log);

        RealtimeInstance = new AVRealtime(config);
        RealtimeInstance.RegisterMessageType <Emoji>();
        RealtimeInstance.RegisterMessageType <NikkiMessage>();
    }
 public void TestInitRealtime()
 {
     //AVClient.Initialize("3knLr8wGGKUBiXpVAwDnryNT-gzGzoHsz", "3RpBhjoPXJjVWvPnVmPyFExt");
     var realtime = new AVRealtime("3knLr8wGGKUBiXpVAwDnryNT-gzGzoHsz", "3RpBhjoPXJjVWvPnVmPyFExt");
     realtime.CreateClient("junwu").ContinueWith(t =>
     {
         var client = t.Result;
         Console.WriteLine(client.State.ToString());
         return Task.FromResult(0);
     }).Unwrap().Wait();
     //var avObject = new AVObject("TestObject");
     //avObject["key"] = "value";
     //return avObject.SaveAsync().ContinueWith(t =>
     //{
     //    Console.WriteLine(avObject.ObjectId);
     //    return Task.FromResult(0);
     //}).Unwrap();
 }
Beispiel #24
0
 public void Send(string message)
 {
     if (connection != null)
     {
         if (this.IsOpen)
         {
             connection.Send(message);
         }
         else
         {
             var log = "Connection is NOT open when send message";
             AVRealtime.PrintLog(log);
             connection?.Close();
         }
     }
     else
     {
         AVRealtime.PrintLog("Connection is NULL");
     }
 }
        public async Task OnExecuteAsync(CommandLineApplication app, IConsole console)
        {
            AVClient.Initialize(AppId, AppKey);
            AVRealtime.WebSocketLog((str) =>
            {
                console.WriteLine(str);
            });

            AVRealtime realtime = new AVRealtime(AppId, AppKey);

            AVIMClient client = await realtime.CreateClientAsync(ClientId);

            var conversation = await client.GetConversationAsync("5b83a01a5b90c830ff80aea4");

            await conversation.SendImageAsync("http://ww3.sinaimg.cn/bmiddle/596b0666gw1ed70eavm5tg20bq06m7wi.gif", "Satomi_Ishihara", "萌妹子一枚", new Dictionary <string, object>
            {
                { "actress", "石原里美" }
            });

            new RealtimeCommand().OnExecute(app, console);
        }
Beispiel #26
0
        public async Task InitChatSDK()
        {
            string userid = string.Empty;
            string roomid = string.Empty;

            try
            {
                userid = VenueRtcCLI.VenueRTC.Instance.getUserId();
                roomid = VenueRtcCLI.VenueRTC.Instance.getRoomId();
            }
            catch (Exception ex)
            {
                App.LogError(ex);
            }
            AVClient.Initialize("Q2BQPmQMCARUy2LY6pqc8Tk3-gzGzoHsz", "5jl51fyVTMUhHt6ddghrXNTa");
            AVRealtime realtime = new AVRealtime("Q2BQPmQMCARUy2LY6pqc8Tk3-gzGzoHsz", "5jl51fyVTMUhHt6ddghrXNTa");

            Websockets.Net.WebsocketConnection.Link();
            vIMClient = await realtime.CreateClientAsync(userid);

            AVIMConversationQuery   query         = vIMClient.GetChatRoomQuery().WhereEqualTo("name", roomid);
            List <AVIMConversation> conversations = (List <AVIMConversation>)(await query.FindAsync());

            if (conversations == null || conversations.Count == 0)
            {
                conversation = await vIMClient.CreateChatRoomAsync(roomid);
            }
            else
            {
                conversation = conversations[0];
            }

            await vIMClient.JoinAsync(conversation);

            await getHistoryMessage();

            vIMClient.OnMessageReceived += VIMClient_OnMessageReceived;
        }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            Websockets.Net.WebsocketConnection.Link();
            //var config = new AVRealtime.Configuration()
            //{
            //    ApplicationId = "021h1hbtd5shlz38pegnpkmq9d3qf8os1vt0nef4f2lxjru8",
            //    ApplicationKey = "3suek8gdtfk3j3dgb42p9o8jhfjkbnmtefk3z9500balmf2e",
            //    SignatureFactory = new LeanEngineSignatureFactory()
            //};
            string appId  = "021h1hbtd5shlz38pegnpkmq9d3qf8os1vt0nef4f2lxjru8";
            string appKey = "3suek8gdtfk3j3dgb42p9o8jhfjkbnmtefk3z9500balmf2e";
            var    config = new AVRealtime.Configuration()
            {
                ApplicationId  = appId,
                ApplicationKey = appKey,
                //SignatureFactory = new LeanEngineSignatureFactory()
            };

            realtime = new AVRealtime(config);
            realtime.RegisterMessageType <Emoji>();
            realtime.RegisterMessageType <EmojiV2>();
            realtime.RegisterMessageType <BinaryMessage>();

            this.CenterContent = new LogIn();
            var logInVM = ServiceLocator.Current.GetInstance <LogInViewModel>();

            logInVM.realtime = realtime;
            logInVM.client   = CurrentClient;

            logInVM.PropertyChanged += LogInVM_PropertyChanged;

            this.LogContent = new WebSocketLog();
            var logVM = ServiceLocator.Current.GetInstance <WebSocketLogViewModel>();

            var teamVM = ServiceLocator.Current.GetInstance <TeamViewModel>();

            teamVM.PropertyChanged += TeamVM_PropertyChanged;
        }
Beispiel #28
0
        static async void Test()
        {
            AVRealtime.WebSocketLog(Console.WriteLine);

            Websockets.Net.WebsocketConnection.Link();
            var appId  = "Eohx7L4EMfe4xmairXeT7q1w-gzGzoHsz";
            var appKey = "GSBSGpYH9FsRdCss8TGQed0F";

            AVClient.Initialize(appId, appKey);
            var realtime = new AVRealtime(appId, appKey);
            var client   = await realtime.CreateClientAsync("lean");

            client.OnMessageReceived += (sender, e) => {
                var msg = e.Message;
                if (msg is AVIMMessage)
                {
                    Console.WriteLine((msg as AVIMMessage).Content);
                }
            };
            var conv = await client.CreateConversationAsync("cloud");

            Console.WriteLine($"conversation id: {conv.ConversationId}");
        }
Beispiel #29
0
 private void Connection_OnError(string obj)
 {
     AVRealtime.PrintLog($"PCL websocket error:  {obj}");
     connection?.Close();
 }
Beispiel #30
0
 private void Connection_OnClosed()
 {
     AVRealtime.PrintLog("PCL websocket closed without parameters..");
     OnClosed?.Invoke(0, "", "");
 }
Beispiel #31
0
 private void Connection_OnMessage(string obj)
 {
     AVRealtime.PrintLog("websocket<=" + obj);
     OnMessage?.Invoke(obj);
 }