示例#1
0
        /// <summary>
        /// Initializes the socket and sets-up all the events to listen to.
        /// Server certifaction validation is ingnored, because the server uses a self-signed certificate.
        /// </summary>
        /// <param name="adress"></param>
        public void Initialize(string adress, bool ignoreServerCertificateValidation) {
            _socket = IO.Socket(adress, new IO.Options() { Secure = true, IgnoreServerCertificateValidation = ignoreServerCertificateValidation });

            _socket.On("register-accepted", (data) => {
                Console.WriteLine("Succesfull connected with Server");
            });
            _socket.On("register-failed", (data) => {
                string errorMessage = data.ToString();
                Console.WriteLine("Failed to connected with Server: {0}", errorMessage);
            });
            _socket.On("message", (data) => {
                var message = JsonConvert.DeserializeObject<JsonReceivedMessage>(data.ToString());
                OnMessageReceived(this, new MessageReceivedEventArgs() { Identifier = message.Sender, Message = message.Message, TimeStamp = message.Timestamp, GroupHash = message.GroupHash });
            });
            _socket.On("user-search", (data) => {
                List<Client> clients = JsonConvert.DeserializeObject<List<Client>>(data.ToString());
                OnUserSearch(this, new UserSearchEventArgs() { FoundMembers = clients });
            });
            _socket.On("user-confirm", (data) => {
                var client = JsonConvert.DeserializeObject<Client>(data.ToString());
                OnUserConfirm(this, new UserConfirmEventArgs() { PublicKey = client.PublicKey, UserName = client.UserName });
            });
            _socket.On("joined-group", (data) => {
                var message = JsonConvert.DeserializeObject<JsonJoinedGroup>(data.ToString());
                OnGroupJoined(this, new GroupJoinedEventArgs() { GroupName = message.GroupName, GroupHash = message.GroupHash, Members = message.Members });
            });

            _socket.Connect();
        }
        public void Login(string username)
        {
            if (socket != null)
            {
                socket.Close();
            }

            socket = IO.Socket("http://chat.socket.io/");
            socket.Connect();

            var alert = new AlertDialog.Builder(this).SetMessage("Logging in...").Show();
            var chat = new ChatFragment(username, socket, alert);
            FragmentManager.BeginTransaction()
                           .Replace(Resource.Id.frameLayout, chat)
                           .Commit();

            // Tell the server your username (login)
            socket.Emit("add user", username);
        }
示例#3
0
        public void connectInternet()
        {
            mSocket = IO.Socket(this.LocalHost);
            if (this.checkConnect == false)
            {
                this.checkConnect = true;
                mSocket.Connect();
            }

            mSocket.On(Socket.EVENT_CONNECT, () =>
            {
                BeginInvoke((Action)(() =>
                {
                    Debug.WriteLine("OK");
                    this.tb_StatusConnection.Text = "Kết nối thành công Internet.!";
                }), null);
            });

            mSocket.On(Socket.EVENT_DISCONNECT, () =>
            {
                BeginInvoke((Action)(() =>
                {
                    this.tb_StatusConnection.Text = "Ngắt kết nối.!";
                }), null);
            });

            mSocket.On("Doc danh sach phong choi", (data) =>
            {
                BeginInvoke((Action)(() =>
                {
                    string[] danhsachphong = data.ToString().Split('|');
                    this.lb_DanhSachPhong.Items.Clear();
                    foreach (var phong in danhsachphong)
                        if (!String.IsNullOrWhiteSpace(phong))
                            this.lb_DanhSachPhong.Items.Add(phong);
                }), null);
            });
        }
示例#4
0
        public void Connect(string token)
        {
            // Set options
            _opt = new IO.Options
            {
                Transports  = ImmutableList.Create("websocket"),
                AutoConnect = false,
                Query       = new Dictionary <string, string>
                {
                    { "token", token }
                }
            };

            // Socket IO with URI and Options
            _sio = IO.Socket(_uri, _opt);

            // Attach SocketIO events
            _sio.On(SocketIO.EVENT_CONNECT, () => SocketConnected());
            _sio.On(SocketIO.EVENT_DISCONNECT, () => SocketDisconnected());
            _sio.On("event", (data) => SocketEvent(data));

            // Connect
            _sio.Connect();
        }
示例#5
0
        public LinkIO connect(Action<LinkIO> listener)
        {
            IO.Options opts = new IO.Options();
            Dictionary<String, String> query = new Dictionary<String, String>();
            if(mail != "")
				query.Add("mail", mail);

            if (password != "")
                query.Add("password", password);
			
			query.Add("api_key", api_key);
			
            opts.Query = query;
            opts.AutoConnect = false;
            opts.Transports = ImmutableList.Create<string>(WebSocket.NAME, Polling.NAME);

            socket = IO.Socket("http://" + serverIP, opts);

            socket.On("users", (e) =>
            {
                List<User> users = ((JArray)e).ToObject<List<User>>();
                if (users.Count > usersInRoom.Count)
                {
                    foreach(User user1 in users)
                    {
                        bool found = false;
                        foreach(User user2 in usersInRoom)
                        {
                            if (user1.ID == user2.ID)
                                found = true;
                        }
                        if (!found)
                            userJoinListener.Invoke(user1);
                    }
                }
                else
                {
                    foreach (User user1 in usersInRoom)
                    {
                        bool found = false;
                        foreach (User user2 in users)
                        {
                            if (user1.ID == user2.ID)
                                found = true;
                        }

                        if (!found)
                            userLeftListener.Invoke(user1);
                    }
                }

                usersInRoom = users;
            });
			
			socket.On("error", (Object o) =>
            {
                if (errorHandler != null)
                {
                    string message = (string)((JValue)o);
                    message = message.Replace("\"", "");

                    switch (((string)((JValue)o)).Replace("\"", ""))
                    {
                        case "ACCOUNT ERROR":
                            errorHandler.Invoke(new AccountNotFoundException("Email does not match any account in API."));
                            break;
                        case "PASSWORD ERROR":
                            errorHandler.Invoke(new WrongPasswordException("Password does not match the given Email."));
                            break;
                        case "API_KEY ERROR":
                        default:
                            errorHandler.Invoke(new WrongAPIKeyException("The application does not match with an API key."));
                            break;
                    }
                }
            });

            socket.On("info", (Object o) =>
            {
                JObject evt = (JObject)o;

                currentUser = new User()
                {
                    Name = (String)evt.SelectToken("name"),
                    FirstName = (String)evt.SelectToken("firstname"),
                    Mail = (String)evt.SelectToken("mail"),
                    ID = (String)evt.SelectToken("id"),
                    Role = (String)evt.SelectToken("role")
                };

                Task.Run(() =>
                {
                    connected = true;
                    listener.Invoke(this);
                });
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                connected = false;
            });

            socket.On("event", (Object o) =>
            {
                JObject evt = (JObject)o;
                String eventName = (String)evt.SelectToken("type");
                if (eventListeners.ContainsKey(eventName))
                {
                    Task.Run(() =>
                    {
                        eventListeners[eventName].Invoke(new Event(evt, cSharpBinarySerializer));
                    });
                }


            });
            
            socket.Connect();

            return this;
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			if (socket != null) {
				socket.Close ();
			}

			socket = IO.Socket ("http://chat.socket.io/");
			socket.Connect ();

			var alert = new UIAlertView ("Log in", "Logging in...", null, null, null);
			alert.Show ();

			AttachSocketEvents (alert);

			// Tell the server your username (login)
			socket.Emit ("add user", Username);

			entryText.Selected = true;
			entryText.Started += (sender, e) => {
				if (connected) {
					if (!typing) {
						typing = true;
						socket.Emit ("typing");
					}
				}
			};
			entryText.Ended += (sender, e) => {
				if (connected) {
					if (typing) {
						socket.Emit ("stop typing");
						typing = false;
					}
				}
			};
			sendButton.TouchUpInside += (sender, e) => {
				SendMessage ();
				socket.Emit ("stop typing");
				typing = false;
			};

			// scroll up when the keyboard appears
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, notification => {
				var info = notification.UserInfo;
				var kbFrame = (NSValue)info [UIKeyboard.FrameEndUserInfoKey];
				var kbDuration = (NSNumber)info [UIKeyboard.AnimationDurationUserInfoKey];
				var animationDuration = kbDuration.DoubleValue;
				var keyboardFrame = kbFrame.CGRectValue;

				nfloat height = keyboardFrame.Size.Height + 8;

				entryTextBottom.Constant = height;
				sendButtonBottom.Constant = height;

				UIView.Animate (animationDuration, () => View.LayoutIfNeeded ());
			});
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, notification => {
				var info = notification.UserInfo;
				var kbDuration = (NSNumber)info [UIKeyboard.AnimationDurationUserInfoKey];
				var animationDuration = kbDuration.DoubleValue;

				entryTextBottom.Constant = 8;
				sendButtonBottom.Constant = 8;

				UIView.Animate (animationDuration, () => View.LayoutIfNeeded ());
			});
		}
示例#7
0
        public void connectSocket()
        {
            if (this.TOKEN != null)
                {
                    try
                    {
                        Dictionary<string, string> _author = new Dictionary<string, string>();
                        _author.Add("token", this.TOKEN);
                        IO.Options _option = new IO.Options();
                        //_option.Timeout = 5000;
                        _option.Query = _author;
                        _option.ForceNew = true;
                        _option.Reconnection = true;
                        _option.ReconnectionDelay = 500;

                        mSocket = IO.Socket(HOSTNAME, _option);
                        mSocket.On(Socket.EVENT_CONNECT, () =>
                        {
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                              //  MessageBox.Show("OK");
                            });
                            Debug.WriteLine("OK");
                        });
                        mSocket.On(Socket.EVENT_CONNECT_ERROR, onConnectError);
                        mSocket.On(Socket.EVENT_CONNECT_TIMEOUT, onConnectTimeout);
                        mSocket.On(Socket.EVENT_ERROR, () =>
                        {
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                               // MessageBox.Show("ERROR");
                                mSocket.Connect();
                                mSocket.Open();
                            });
                        });
                        mSocket.On(Constant.SOCKET_EVENT_JOIN, onJoinRoom);
                        mSocket.On(Constant.SOCKET_EVENT_ADD, onAddUser);
                        mSocket.On(Constant.SOCKET_EVENT_LEAVE, onLeaveRoom);
                        mSocket.On(Constant.SOCKET_EVENT_CHANGE_ROOM_TITLE, onChangeRoomTitle);
                        mSocket.On(Constant.SOCKET_EVENT_CHAT, (data) => {
                            Debug.WriteLine(data.ToString());
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                                String result = data.ToString();
                                ChatResponse resultObject = JsonConvert.DeserializeObject<ChatResponse>(result);
                                if(resultObject.data.message.type == 2)
                                {
                                    App.ViewModel.Items.Add(new ViewModels.ItemViewModel() { SenderID = resultObject.data.sender._id, CreateAt = resultObject.data.sequence, MessageText = resultObject.data.message.message, Avatar = new Uri(resultObject.data.sender.avatar), Type = resultObject.data.message.type, thumbnail = new Uri(resultObject.data.message.file.thumbnail, UriKind.RelativeOrAbsolute) });
                                }
                                else
                                {
                                    App.ViewModel.Items.Add(new ViewModels.ItemViewModel() { SenderID = resultObject.data.sender._id, CreateAt = resultObject.data.sequence, MessageText = resultObject.data.message.message, Avatar = new Uri(resultObject.data.sender.avatar), Type = resultObject.data.message.type });
                                }

                                if(resultObject.data.sender._id != App._userid)
                                {
                                    var stream = Application.GetResourceStream(new Uri(@"Assets/Audio/recieve.wav", UriKind.RelativeOrAbsolute));
                                    var effect = SoundEffect.FromStream(stream.Stream);
                                    var soundInstance = effect.CreateInstance();

                                    FrameworkDispatcher.Update();
                                    soundInstance.Play();
                                    App._reuserid = resultObject.data.sender._id;
                                    ToastPrompt tost = new ToastPrompt()
                                    {
                                        Title = resultObject.data.sender.username,
                                        Message = resultObject.data.message.message,
                                    };
                                    tost.Tap += tosk_Tap;
                                    tost.Show();
                                }
                            });
                        });
                        mSocket.Connect();
                    }
                catch(Exception e)
                    {
                        Debug.WriteLine("IO exception  " + e.Message);
                        //mSocket.Close();
                       // mSocket.Open();
                    }
                }
                else
                {
                    Debug.WriteLine("No token found!");
                }
        }
示例#8
0
        public LinkIO connect(Action listener)
        {
            IO.Options opts = new IO.Options();
            Dictionary<String, String> query = new Dictionary<String, String>();
            query.Add("user", user);

            if(id != "")
                query.Add("id", id);

            opts.Query = query;
            opts.AutoConnect = false;

            socket = IO.Socket("http://" + serverIP, opts);

            socket.On("users", (e) =>
            {
                if (userInRoomChangedListener != null)
                    userInRoomChangedListener.Invoke(((JArray) e).ToObject<List<User>>());
            });

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                connected = true;
                listener.Invoke();
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                connected = false;
            });

            socket.On("event", (Object o) =>
            {
                JObject evt = (JObject) o;
                String eventName = (String) evt.SelectToken("type");
                if (eventListeners.ContainsKey(eventName))
                {
                    eventListeners[eventName].Invoke(new Event(evt));
                }                        


            });

            socket.Connect();

            return this;
        }
示例#9
0
 public Socket(MainWindow window)
 {
     this.window = window;
     socket      = IO.Socket("http://localhost:3003");
     socket.Connect();
 }