Exemplo n.º 1
0
 /// <summary>
 /// NotifyChangeToAllClients.
 /// notify all the clients about the command.
 /// </summary>
 /// <param name="args">CommandRecievedEventArgs</param>
 private void NotifyChangeToAllClients(CommandRecievedEventArgs args)
 {
     foreach (TcpClient client in clientsList)
     {
         new Task(() =>
         {
             try
             {
                 NetworkStream stream = client.GetStream();
                 BinaryReader reader  = new BinaryReader(stream);
                 BinaryWriter writer  = new BinaryWriter(stream);
                 //write the command to the clients.
                 WriteMutex.WaitOne();
                 writer.Write(JsonConvert.SerializeObject(args));
                 WriteMutex.ReleaseMutex();
             } catch (Exception e)
             {
                 //remove the problematic client from clients list
                 ClientsListMutex.WaitOne();
                 clientsList.Remove(client);
                 ClientsListMutex.ReleaseMutex();
                 // log failure
                 this.m_logging.Log(e.ToString(), MessageTypeEnum.FAIL);
                 this.m_logging.Log("One of clients seems to be offline", MessageTypeEnum.FAIL);
                 //!will continue treating next client naturally!
             }
         }).Start();
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// HandleClient.
 /// handle with a client(in different thread).
 /// </summary>
 /// <param name="client">TcpClient</param>
 private void HandleClient(TcpClient client)
 {
     new Task(() =>
     {
         try
         {
             NetworkStream stream = client.GetStream();
             BinaryReader reader  = new BinaryReader(stream);
             BinaryWriter writer  = new BinaryWriter(stream);
             bool successFlag;
             string result;
             while (true)
             {
                 //read client data request in the form of a command, then return data
                 String rawData = reader.ReadString();
                 CommandRecievedEventArgs commandArgs = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(rawData);
                 //execute the command.
                 result = m_controller.ExecuteCommand(commandArgs.CommandID, commandArgs.Args, out successFlag);
                 //write the result to the client.
                 WriteMutex.WaitOne();
                 writer.Write(result);
                 WriteMutex.ReleaseMutex();
             }
         }
         catch (Exception e)
         {
             //remove the problematic client from clients list
             ClientsListMutex.WaitOne();
             clientsList.Remove(client);
             ClientsListMutex.ReleaseMutex();
             //log failure
             this.m_logging.Log("One of clients seems to be offline", MessageTypeEnum.FAIL);
             return;
         }
     }).Start();
 }
 public void Dispose()
 {
     WriteMutex.Release();
 }