コード例 #1
0
        /// <summary>
        /// Accept a new user, search a free user name and inform the other users
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="socketId"></param>
        /// <returns></returns>
        private async Task AcceptNewUser(WebSocket socket, string socketId)
        {
            ChatPartner newChatPartner = new ChatPartner()
            {
                WebSocket = socket,
            };

            lock (_sockets)
            {
                newChatPartner.Nickname   = GetFreeNickname("anonymous");
                newChatPartner.Identifier = socketId;
                _sockets.TryAdd(socketId, newChatPartner);
            }

            _globalRoom.ConnectedUsers.Add(newChatPartner.Identifier);

            UserJoinMessage joinMessage = new UserJoinMessage()
            {
                SenderGuid        = socketId,
                IsOriginOfMessage = false,
                ChatUser          = newChatPartner
            };

            await InformUsersAboutJoin(joinMessage, _globalRoom);
        }
コード例 #2
0
        private void DataReceivedCallback(object sender, UDPDataReceivedEventArgs e)
        {
            using (stream = new MemoryStream())
            {
                stream.Write(e.Data, 0, e.Data.Length);
                stream.Position = 0;

                try
                {
                    Message     msg     = (Message)this.formatter.Deserialize(stream);
                    ChatPartner partner = msg.Parse();

                    foreach (var chat in this.ConnectedClients.Where(p => p.Partner == partner))
                    {
                        chat.msgHistory.Add(msg.Text);
                        return;
                    }
                    ChatPartnerVM newchatpartnervm = new ChatPartnerVM(partner);
                    newchatpartnervm.OnConnect += this.DirectConnectOnEvent;
                    this.DiscoveredClients.Add(newchatpartnervm);
                }
                catch (InvalidCastException)
                {
                    Debug.WriteLine("Invalid Cast on Broadcast.");
                }
            }
        }
コード例 #3
0
        public void DirectConnectOnEvent(object sender, EventArgs args)
        {
            ChatWindow  chatWindow = new ChatWindow();
            ChatPartner partner    = ((ChatPartnerVM)sender).Partner;
            ChatVM      chatvm     = new ChatVM(partner);

            chatWindow.DataContext = chatvm;
            chatWindow.Show();
        }
コード例 #4
0
        public void DirectConnect()
        {
            ChatWindow  chatWindow = new ChatWindow();
            ChatPartner partner    = new ChatPartner("New_Partner", IPAddress.Parse(this.CurrentIp), Convert.ToInt16(this.CurrentPort));
            ChatVM      chatvm     = new ChatVM(partner);

            chatWindow.DataContext = chatvm;
            chatWindow.Show();
        }
コード例 #5
0
        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            ChatPartner partner = (ChatPartner)obj;

            partner.PCName = info.GetString("PCName");
            partner.Port   = info.GetInt16("Port");
            partner.Ip     = (IPAddress)info.GetValue("Ip", IPAddress.None.GetType());
            return(partner);
        }
コード例 #6
0
        /// <summary>
        /// Closes the user's websocket, removes him from the server and informs the other users that he is disconnected
        /// </summary>
        /// <param name="userIdentifier"></param>
        /// <returns></returns>
        public async Task DisconnectUserFromServer(string userIdentifier)
        {
            bool        proceedWithDisconnect = false;
            ChatPartner user = null;

            lock (_userRemovalLockObject) {
                //the socket still has to be in our socket-dictionary and shouldn't be in the list of currently disconnecting users
                if (_sockets.TryRemove(userIdentifier, out user) && !_queuedUsersToDisconnect.Contains(userIdentifier))
                {
                    _queuedUsersToDisconnect.Add(userIdentifier);
                    proceedWithDisconnect = true;
                }
                else
                {
                    _queuedUsersToDisconnect.Remove(userIdentifier);
                }
            }

            if (proceedWithDisconnect)
            {
                try
                {
                    await RemoveUserFromAllChatRooms(userIdentifier);

                    Task closeTask = user.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    closeTask.Wait();
                    user.WebSocket.Dispose();
                }
                catch (Exception ex)
                {
                    //catch errors (if the closing of the socket fails)
                }

                UserLeaveMessage message = new UserLeaveMessage()
                {
                    RoomIdentifier = _globalRoom.RoomIdentifier,
                    SenderGuid     = userIdentifier
                };

                await InformServerAboutLeavingUser(message);

                lock (_userRemovalLockObject)
                {
                    _queuedUsersToDisconnect.Remove(userIdentifier);
                }
            }
        }
コード例 #7
0
        public async Task <IHttpActionResult> SetChatPartner([FromBody] ChatPartner i_Partner)
        {
            string nickname = Thread.CurrentPrincipal.Identity.Name;

            using (CarWatchDBEntities entities = new CarWatchDBEntities())
            {
                FacebookAccount account = await entities.FacebookAccounts.FirstOrDefaultAsync(e => e.Nickname == nickname);

                if (account == null)
                {
                    return(BadRequest("This nickname is not registered."));
                }
                account.ChatPartner = i_Partner.Partner;
                await entities.SaveChangesAsync();

                return(Ok());
            }
        }
コード例 #8
0
ファイル: ChatPartnerVM.cs プロジェクト: gschranz/P2PChat
 public ChatPartnerVM(ChatPartner partner)
 {
     this.cp             = partner;
     this.connectCommand = new ConnectCommand(this);
 }
コード例 #9
0
 public ChatVM(ChatPartner partner)
 {
     this.Partner    = partner;
     this.msgHistory = new ObservableCollection <string>();
     Task maintask = Task.Run(() => SimpleChatting());
 }