/// <summary> /// Removes the user from the active users in the server and updates the friend list with users who are friends with him. /// </summary> /// <returns></returns> public bool Logout() { try { IClientCallback callback = OperationContext.Current.GetCallbackChannel <IClientCallback>(); UserInformation user = Subscriber.subscribers.Find(x => x.CommunicationCallback == callback); Subscriber.Unsubscribe(callback); foreach (UserInformation client in Subscriber.subscribers) { if (client.IsFriendWith(user.Username) && user.CommunicationCallback != client.CommunicationCallback) { client.CommunicationCallback.UpdateListOfContacts(user.Username); } } using (DataBaseContainer context = new DataBaseContainer()) { User client = context.Users.ToList().Find(x => x.Username == user.Username); client.Status = 0; context.SaveChanges(); } return(true); } catch { return(false); } }
Dictionary <IClientCallback, string> userList = new Dictionary <IClientCallback, string>(); //Menyimpan data ketika online public void gabung(string username) { //untuk menampung user ketika baru daftar/buat akun IClientCallback koneksiGabung = OperationContext.Current.GetCallbackChannel <IClientCallback>(); userList[koneksiGabung] = username; }
public void SendMessageInternal(IClientCallback client, int requestId, string roomName, string messageText) { var userId = GetUserId(client); if (userId == -1) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.UnknownUser) }), lockTimeout); return; } var errorCode = SendMessageWithNoAnswer(userId, roomName, messageText, requestId); if (errorCode != ChatResultCode.Ok) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, errorCode) }), lockTimeout); return; } answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.Ok) }), lockTimeout); }
public void GetAllUsersInternal(IClientCallback client, int requestId, string roomName) { ChatResultCode errorCode; var answer = new AnswerWithUsers { RequestId = requestId, Status = ChatResultCode.Ok, Room = roomName, Users = GetData4GetAllUsers(roomName, requestId, out errorCode) }; if (errorCode != ChatResultCode.Ok) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, errorCode) }), lockTimeout); return; } answers.InQueue(new ChatAnswer(client, AnswerCode.AllUsersReceived, new List <object> { answer }), lockTimeout); }
public void AddClient(string sessionId, IClientCallback callback) { if (!_callbackList.ContainsKey(sessionId)) { _callbackList.Add(sessionId, callback); } }
/// <summary> /// Creates a friend request. /// </summary> /// <param name="username">The username of the friend</param> public void AddFriend(string username) { IClientCallback clientCallback = OperationContext.Current.GetCallbackChannel <IClientCallback>(); using (DataBaseContainer context = new DataBaseContainer()) { User user = context.Users.ToList().Find(x => x.Username == username); UserInformation clientRequest = Subscriber.subscribers.ToList().Find(x => x.CommunicationCallback == clientCallback); User sender = context.Users.ToList().Find(x => x.Username == clientRequest.Username); Request request = new Request(); request.FromUserId = sender.IdUser; request.FromUsername = sender.Username; request.User = user; user.Requests.Add(request); context.SaveChanges(); UserInformation _user = Subscriber.subscribers.Find(x => x.Username == user.Username); if (_user != null) { _user.ScreenShareCallback.SendFriendNotification(sender.Username, sender.UserAvatar.Image); } } }
//----------------------------------------------------------------------------------------- IStockService public void RegisterForUpdates(string ticker) { Worker w = null; // при необходимости создаём новый рабочий объект, добавляем его // в хэш-таблицу и запускаем в отдельном потоке if (!workers.ContainsKey(ticker)) { w = new Worker(); w.ticker = ticker; w.workerProcess = new Update(); w.workerProcess.ticker = ticker; workers[ticker] = w; Thread t = new Thread(new ThreadStart(w.workerProcess.SendUpdateToClient)); t.IsBackground = true; t.Start(); } // получить рабочий объект для данного тикера и добавить // прокси клиента в список обработанных вызовов w = (Worker)workers[ticker]; IClientCallback c = OperationContext.Current.GetCallbackChannel <IClientCallback>(); lock (w.workerProcess.callbacks) w.workerProcess.callbacks.Add(c); }
public void addClientCallBack(IClientCallback cc) { lock (m_clientCallbacks) { m_clientCallbacks.Add(cc); } }
public void delClientCallBack(IClientCallback cc) { lock (m_clientCallbacks) { m_clientCallbacks.Remove(cc); } }
public void Disconnect() { m_FreeSocket = true; ShutDown(); m_ClientCallback = null; PTZLogger.Log.Debug("{0},{1}, Socket channel closed", m_Name, m_Host); }
private void TryCatchWrapper(Action Act, IClientCallback Obj) { try { Act(); } catch (ObjectDisposedException) { m_SubToDelete = Obj; } catch (CommunicationObjectAbortedException) { m_SubToDelete = Obj; } catch (CommunicationObjectFaultedException) { m_SubToDelete = Obj; } catch (Exception ex) { SystemHost.Journal.AppendLog(ComplexParts.None, LogMessageType.Error, String.Format(Resources.Error_BroadcastCommunication_Exception_during_callback_action, ex.GetType(), ex.Message)); m_SubToDelete = Obj; } }
/*public void StartGame() * { * this.gameTask = Task.Factory.StartNew(() => * { * this.State = States.Running; * try * { * Debug.Print("Start Game"); * * var gameData = GameInitializationDataBuilder.Build(this.gameManager.Board); * foreach (var client in this.clients) * { * client.InitializeGame(gameData); * } * * // Clients confirming that they have completed game initialization. * var awaitingGameInitializationConfirmation = new HashSet<IServiceProviderCallback>(this.clients); * GameSessionMessage message = null; * while (awaitingGameInitializationConfirmation.Count > 0) * { * this.cancellationToken.ThrowIfCancellationRequested(); * * if (this.messagePump.TryDequeue(GameSessionMessage.Types.ConfirmGameInitialized, out message)) * { * awaitingGameInitializationConfirmation.Remove(message.Client); * Debug.Print("Received: " + awaitingGameInitializationConfirmation.Count + " left."); * continue; * } * * Thread.Sleep(50); * } * * // Clients have all confirmed they received game initialization data * // Now ask each client to place a town in dice roll order. * this.PlaceTownsInFirstPassOrder(this.gameManager.GetFirstSetupPassOrder()); * * // Do second pass of setup * this.PlaceTownsInSecondPassOrder(); * } * catch (OperationCanceledException) * { * // Shutting down - ignore exception * this.State = States.Stopping; * } * finally * { * this.State = States.Stopped; * } * }); * }*/ private Boolean AddPlayer(IClientCallback client, String username) { for (var i = 0; i < this.clients.Length; i++) { if (this.clients[i] != null) { continue; } this.clients[i] = client; client.ConfirmGameSessionJoined(this.GameSessionToken, GameStates.Lobby); var playerCard = this.playerCardRepository.GetPlayerData(username); this.currentPlayerCount++; if (this.currentPlayerCount > 1) { this.SendPlayerDataToPlayers(i, client, playerCard); } this.playerCards.Add(client, playerCard); return(this.currentPlayerCount == this.clients.Length); } return(true); }
private LoginOperationResult Login(User user, IClientCallback clientCallback) { var newClientConnection = new ClientConnection { Callback = clientCallback, User = user }; if (_clients.TryAdd(user.Login, newClientConnection)) { foreach (var conn in _clients.Where(c => c.Value != newClientConnection)) { conn.Value.Callback.UserLoggedIn(newClientConnection.User); } return(new LoginOperationResult { User = newClientConnection.User }); } return(new LoginOperationResult { OperationResult = OperationResult.Failure, Message = "Не удалось зврегистрировать клиентское соединение." }); }
public void LoadClientListener(IClientCallback cb) { new Thread(t => { factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: clientQueue, durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Debug.WriteLine(" [x] Received On Client: " + message); Response r = JObject.Parse(message).ToObject <Response>(); new Task(new Action(() => { cb.Handle(r); })).Start(); }; channel.BasicConsume(queue: clientQueue, noAck: true, consumer: consumer); while (true) { } } } ).Start(); }
public User(string name, IClientCallback clientCallback, IClientChannel clientChannel) { Name = name; this._clientCallback = clientCallback; IsReady = false; this._clientChannel = clientChannel; }
public void CreateRoomInternal(IClientCallback client, int requestId, Room room, bool detectOwner = true) { if (string.IsNullOrEmpty(room.Name)) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.Error) }), lockTimeout); return; } bool timeoutFlag; if (rooms.Contains(room, lockTimeout, out timeoutFlag)) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.RoomExists) }), lockTimeout); return; } // устанавливаем владельца var user = users.Find(u => u.ClientCallback == client, lockTimeout); if (user == null) { answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.UnknownUser) }), lockTimeout); return; } // администратор может устанавливать любого владельца // а ткаже выставлять флаг сохранения комнаты даже в случае неактивности if (((int)user.RoleMask & (int)UserRole.Administrator) == 0) { room.Owner = user.ID; room.IsBound = false; } // указанный владелец не существует if (users.Find(u => u.ID == room.Owner, lockTimeout) == null) { room.Owner = user.ID; } answers.InQueue( new ChatAnswer(client, AnswerCode.RequestStatusReceived, new List <object> { new Answer(requestId, ChatResultCode.Ok) }), lockTimeout); CreateRoomInternal(room); }
public void SendData(string message) { if (CallbackChannels.Count > 0) { IClientCallback callbackChannel = CallbackChannels[0]; callbackChannel.CallToMyClient(message); } }
private void HandleSubToDelete() { if (m_SubToDelete != null) { m_Subscribers.Remove(m_SubToDelete); m_SubToDelete = null; } }
public void UnsubscribeClient() { IClientCallback channel = OperationContext.Current.GetCallbackChannel <IClientCallback>(); if (CallbackChannels.Contains(channel)) { CallbackChannels.Remove(channel); } }
public void SubscribeClient() { IClientCallback channel = OperationContext.Current.GetCallbackChannel <IClientCallback>(); if (!CallbackChannels.Contains(channel)) { CallbackChannels.Add(channel); } }
public static void MessagingToClient(int Period, int Number, IClientCallback CurrentCallback) { for (int counter = 0; counter < Period; ++counter) { Thread.Sleep(Period * OneSecond); DateTime TimeOnWCFserver = DateTime.Now; CurrentCallback.ReceiveTime(TimeOnWCFserver); } }
public void AddUser(TIdType id, string name, IClientCallback clientCallback, IClientChannel clientChannel) { if (_userDict.ContainsKey(id)) { return; } _userDict.TryAdd(id, new User(name, clientCallback, clientChannel)); }
/// <summary> /// Records that the client has sent the expected message. /// </summary> /// <param name="client">Client that has sent the expected message.</param> /// <returns>True if all clients have sent the expected message, otherwise false.</returns> private Boolean AllClientsHaveSentMessage(IClientCallback client) { if (!this.clientsThatReceivedMessages.Contains(client)) { this.clientsThatReceivedMessages.Add(client); } return(this.clientsThatReceivedMessages.Count == this.clients.Length); }
public static void Subscribe(IClientCallback client, string username) { UserInformation user = new UserInformation(client, username); if (!subscribers.Exists(x => x.CommunicationCallback == client)) { subscribers.Add(user); } }
private ExecuteCommandResponse ExecuteCommandCore(ExecuteCommandRequest request) { Trace.WriteLine(string.Format("Executing command {0} on {1}", request.CommandText, request.ClientName)); IClientCallback callback = _registry.Get(request.ClientName); var response = callback.Execute(request); Trace.WriteLine(string.Format("Command completed. Output: {0}\r\n", response.CommandOutput)); return(response); }
// for internal use private int GetUserId(IClientCallback client) { var user = users.Find(u => u.ClientCallback == client, u => new ServerUser(u), lockTimeout); if (user == null) { return(-1); } return(user.ID); }
public void Initialize(string name, string host, int port, IClientCallback callback) { if (!m_Initialized) { m_Name = name; m_Host = host; m_Port = port; m_ClientCallback = callback; m_Initialized = true; } }
private Boolean AlreadyInGameSession(IClientCallback client) { foreach (var gameSession in this.gameSessions.Values) { if (gameSession.ContainsClient(client)) { return(true); } } return(false); }
public static ObservableCollection <UserInfo> UserJoin(UserInfo user, IClientCallback callback) { clients.Add(new ChatClient(user, callback)); foreach (var client in clients) { if (client.User.Id != user.Id) { client.UserJoin(user); } } return(new ObservableCollection <UserInfo>(clients.Select(c => c.User).ToList().Where(c => c.Id != user.Id).ToList())); }
private void SendPersonalMessageToClients(IClientCallback sendingClient, String sender, String text) { for (int i = 0; i < this.clients.Length; i++) { if (clients[i] == null || clients[i] == sendingClient) { continue; } clients[i].ReceivePersonalMessage(sender, text); } }
/// <summary> /// Constructor. /// </summary> /// <param name="callback">Notifies callback from throttle requests.</param> public ControlClientConflateAndThrottle( IClientCallback callback ) { session = Diffusion.Sessions.Principal( "control" ).Password( "password" ) .Open( "ws://diffusion.example.com:80" ); // Create the client control feature with a handler that sets queue thresholds on new connecting clients // and sets a listener for queue events. var clientControl = session.GetClientControlFeature(); // To register a queue event handler, the client session must have the REGISTER_HANDLER and VIEW_SESSION // permissions. clientControl.SetQueueEventHandler( new MyThresholdHandler( clientControl, callback ) ); }
/// <summary> /// Constructor. /// </summary> /// <param name="callback">Notifies callback from throttle requests.</param> public ControlClientConflateAndThrottle(IClientCallback callback) { session = Diffusion.Sessions.Principal("control").Password("password") .Open("ws://diffusion.example.com:80"); // Create the client control feature with a handler that sets queue thresholds on new connecting clients // and sets a listener for queue events. var clientControl = session.GetClientControlFeature(); // To register a queue event handler, the client session must have the REGISTER_HANDLER and VIEW_SESSION // permissions. clientControl.SetQueueEventHandler(new MyThresholdHandler(clientControl, callback)); }
public MyThresholdHandler( IClientControl clientControl, IClientCallback clientCallback ) { theClientControl = clientControl; theClientCallback = clientCallback; }
public Client(IClientCallback callback, string name) { this._callback = callback; this._name = name; this._GUID = Guid.NewGuid().ToString(); callback.LogIn(this._GUID); foreach (var room in Client.Rooms) { callback.RoomCreated(room); } _room = null; _game = null; _ready = false; }
public void LoadClientListener(IClientCallback cb) { new Thread(t => { factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: clientQueue, durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Debug.WriteLine(" [x] Received On Client: " + message); Response r = JObject.Parse(message).ToObject<Response>(); new Task(new Action(() => { cb.Handle(r); })).Start(); }; channel.BasicConsume(queue: clientQueue, noAck: true, consumer: consumer); while (true) { } } } ).Start(); }
public ChatAnswer(IClientCallback client, AnswerCode code, List<object> arguments) { Client = client; Code = code; Arguments = arguments; }
public void ReturnFolderInfoToClient(string Path, IClientCallback CurrentCallback) { string[] ListOfFilesInDirectory = Directory.GetFiles(Path); CurrentCallback.ReceiveFolderInfo(ListOfFilesInDirectory); }
public ClientJoinInfo(string NewClientName, IClientCallback NewClientCallback) { CurrentClientName = NewClientName; CurrentClientCallback = NewClientCallback; }
public ServerUser(ServerUser user) : base(user) { ClientCallback = user.ClientCallback; }