Esempio n. 1
0
        /**************************************************/

        private void SendMessage(IM_Message message)
        {
            try
            {
                IFormatter    binary_formatter = new BinaryFormatter();
                MemoryStream  mem_str          = new MemoryStream();
                NetworkStream network_stream   = new NetworkStream(tcp.Client);

                crypto_stream_writer = new CryptoStream(mem_str, encryptor, CryptoStreamMode.Write);
                binary_formatter.Serialize(crypto_stream_writer, message);

                crypto_stream_writer.FlushFinalBlock();

                byte[] buffer = mem_str.GetBuffer();

                //Send the length
                network_stream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);
                //Send the data
                network_stream.Write(buffer, 0, buffer.Length);
                network_stream.Flush();
            }
            catch (Exception ex)
            {
                //File.AppendAllText("log.txt", "Encrypting: " + ex.Message + Environment.NewLine);
                //Close();
            }
        }
Esempio n. 2
0
 private void MessageWindowRouter(IM_Message message)
 {
     try
     {
         if (MessengerStructure.ContainsKey(message.From))
         {
             MessengerStructure[message.From].rm(message);
         }
         //we only want to Create a new Client if we are to receive anything the user must see
         else if (message.Type == IM_Message.MESSAGE_TYPE_MSG || message.Type == IM_Message.MESSAGE_TYPE_FILE)
         {
             CreateClient(message.From, message);
         }
         else if (message.Type == IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED || message.Type == IM_Message.MESSAGE_TYPE_CLIENT_DISCONNECTED)
         {
             if (MessengerStructure.ContainsKey((string)message))
             {
                 MessengerStructure[(string)message].rm(message);
             }
         }
     }
     catch (Exception)
     {
         //MessageBox.Show(e.Message);
     }
 }
Esempio n. 3
0
 public void Send(IM_Message message)
 {
     if (NameSet)
     {
         message.From = owner_client.Name; //It's from this username
     }
     owner_client.Send(message);
 }
Esempio n. 4
0
        public void Send(IM_Message message)
        {
            SendMessageDelegate send = new SendMessageDelegate(SendMessage);

            IAsyncResult iRes = send.BeginInvoke(message, new AsyncCallback(iAsyncCallbackMethod), null);

            while (!iRes.AsyncWaitHandle.WaitOne(100, true))
            {
                ;
            }
        }
Esempio n. 5
0
        /************Background Worker Methods*************/
        #region Background Worker Threads
        public void background_worker_StartListening(object sender, DoWorkEventArgs e)
        {
            while (!background_worker.CancellationPending)
            {
                try
                {
                    IFormatter   binary_formatter = new BinaryFormatter();
                    MemoryStream mem_str          = new MemoryStream();
                    crypto_stream_reader = new CryptoStream(mem_str, decryptor, CryptoStreamMode.Write);

                    NetworkStream network_stream = new NetworkStream(tcp.Client);

                    byte[] size = new byte[4];
                    network_stream.Read(size, 0, 4);

                    int length = BitConverter.ToInt32(size, 0);

                    byte[] buffer = new byte[BUFFER_SIZE];
                    int    offset = 0, bytes_read = 0;

                    while (length > 0)
                    {
                        bytes_read = network_stream.Read(buffer, 0, BUFFER_SIZE);
                        crypto_stream_reader.Write(buffer, 0, bytes_read);

                        offset += bytes_read;
                        length -= bytes_read;
                    }

                    crypto_stream_reader.Flush();
                    mem_str.Seek(0, SeekOrigin.Begin);

                    IM_Message im = (IM_Message)binary_formatter.Deserialize(mem_str);
                    if (im != null)
                    {
                        background_worker.ReportProgress(0, im);
                    }
                }
                catch (Exception ex)
                {
                    //File.AppendAllText("log.txt", "Decrypting: " + ex.Message + Environment.NewLine);
                    background_worker.CancelAsync();
                    Close();
                }
            }
        }
Esempio n. 6
0
        private void SendClientListUpdateToAll(object custruct)
        {
            ClientUpdateStruct cu_struct = (ClientUpdateStruct)custruct;
            IM_Message         message   = null;

            switch (cu_struct.type)
            {
            case IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED:
                message = new IM_Message("SERVER", String.Empty, IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED, cu_struct.name);
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_DISCONNECTED:
                message = new IM_Message("SERVER", String.Empty, IM_Message.MESSAGE_TYPE_CLIENT_DISCONNECTED, cu_struct.name);
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_NAME_CHANGE:
                //Message will be intercepted so that it's not sent to the client in the TO field
                //NAME_CHANGE messages will not be forwarded
                message = new IM_Message(cu_struct.name, String.Empty, IM_Message.MESSAGE_TYPE_CLIENT_NAME_CHANGE, cu_struct.extra);
                break;

            default:
                break;
            }

            Monitor.Enter(ListLock);

            List <Client> buffer = new List <Client>(
                clients.Cast <Client>() /*.Where(x => !x.Name.StartsWith("_|___|__|___|_"))*/
                );                      //don't want to include temporary names

            foreach (Client c in buffer)
            {
                if (cu_struct.name != c.Name)
                {
                    //Set the TO field here
                    message.To = c.Name;
                    Thread.Sleep(500);
                    c.Send(message);
                }
            }

            Monitor.Exit(ListLock);
        }
Esempio n. 7
0
        /*******************************************************/
        /*******************************************************/
        /*******************************************************/
        /// <summary>
        /// Receive Message from main client
        /// </summary>
        /// <param name="message"></param>
        private void MessageProcessor(object msg)
        {
            IM_Message message = (IM_Message)msg;

            switch (message.Type)
            {
            case IM_Message.MESSAGE_TYPE_MSG:
                SetText(message, message.From);
                Flash();
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_DISCONNECTED:
                msgTextBox.ReadOnly = true;
                button1.Enabled     = false;
                this.Text          += " - OFFLINE";
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED:
                msgTextBox.ReadOnly = false;
                button1.Enabled     = true;
                this.Text           = this.Text.Replace(" - OFFLINE", String.Empty);
                break;
            }
        }
Esempio n. 8
0
        /*******************************************************************/
        /// <summary>
        /// Brain of Server
        /// </summary>
        /// <param name="message"></param>
        private void ProcessReceivedMessages(object msg)
        {
            IM_Message message = (IM_Message)msg;

            Client sender   = clients.WithName(message.From);
            Client receiver = clients.WithName(message.To);


            //if (sender == null || receiver == null) return;
            //SetText("Message Received from " + message.From + ": " + message.Msg);
            switch (message.Type)
            {
            case IM_Message.MESSAGE_TYPE_SETNAME:
                //Client will not use the name requested until the server has confirmed they can
                int type;
                //check to see if requested name is available
                if (clients.WithName(message) == null || ((string)message == String.Empty))
                {
                    SetText(sender.Name + ": SetName: '" + message + "' approved");
                    type = IM_Message.MESSAGE_TYPE_SETNAME_CONFIRMATION_OK;
                    sender.Send(new IM_Message("SERVER", String.Empty, type, message.Data));

                    //Thread.Sleep(1000); //slow things down
                    SynchronizeClient(message.From, message);
                }
                else
                {
                    type = IM_Message.MESSAGE_TYPE_SETNAME_CONFIRMATION_NO;
                    sender.Send(new IM_Message("SERVER", String.Empty, type, message.Data));
                    SetText(sender.Name + ": SetName: '" + message + "' REJECTED");
                }

                //Send back name confirmation to Client

                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_LIST_CONFIRMATION:
                ClientUpdateStruct custruct = new ClientUpdateStruct
                {
                    name = sender.Name,
                    type = IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED
                };


                //Send an update to the other clients
                Thread t2 = new Thread(new ParameterizedThreadStart(SendClientListUpdateToAll));
                t2.Start(custruct);

                LoadListToBox();
                SetText(String.Format("{0} connected", sender.Name));
                break;

            case IM_Message.MESSAGE_TYPE_MSG:
                receiver.Send(new IM_Message(sender.Name, receiver.Name, IM_Message.MESSAGE_TYPE_MSG, message.Data));
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_SHUTTING_DOWN:
                DisconnectFrom(message.From);
                break;

            default:
                break;
            }
        }
Esempio n. 9
0
 private void Initialize(IM_Message message)
 {
     SetText("Initializing...");
     Send(new IM_Message(TempName, "SERVER", IM_Message.MESSAGE_TYPE_SETNAME, owner_client.Name));
 }
Esempio n. 10
0
        private void ProcessReceivedMessages(object msg)
        {
            IM_Message message = (IM_Message)msg;

            SetText("***************\nMessage Received: " + message + "\n***************");

            switch (message.Type)
            {
            case IM_Message.MESSAGE_TYPE_GETNAME:
                Send(new IM_Message(owner_client.Name, "SERVER", IM_Message.MESSAGE_TYPE_SETNAME, owner_client.Name));
                //Initialize(message);
                break;

            case IM_Message.MESSAGE_TYPE_SETNAME:
                //This is our temporary name
                SetText("Temp Name: " + message);
                TempName = message;     //Implicit conversion here
                Initialize(message);
                break;

            case IM_Message.MESSAGE_TYPE_SETNAME_CONFIRMATION_OK:
                //Only acknowledge name if it matches the one requested
                if (message == owner_client.Name)
                {
                    //Everything seemed to have went OK in the Name Acknowledgement
                    NameSet = true;
                    SetText("Name set to " + owner_client.Name);
                    SetStatus("Status: Connected");
                    EnableDisableControls(false);
                }
                else
                {
                    SetStatus("Name could not be verified. Shutting down.");
                    SetText("Name could not be verified");
                    ShuttingDown();
                    EnableDisableControls(true);
                }
                break;

            case IM_Message.MESSAGE_TYPE_SETNAME_CONFIRMATION_NO:
                //YOU MUST REQUEST ANOTHER NAME HERE
                NameSet = false;
                SetText("Name rejected");
                ShuttingDown();     //disconnect from server
                EnableDisableControls(true);
                SetStatus("Request another name!");
                break;

            case IM_Message.MESSAGE_TYPE_MSG:
                MessageWindowRouter(message);
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_LIST:
                //Only will be called when the client connects first
                SetText("Client List: " + (string)message);
                UpdateClientList(((string)message).Split(new char[] { '*' }));
                Send(new IM_Message(owner_client.Name, String.Empty, IM_Message.MESSAGE_TYPE_CLIENT_LIST_CONFIRMATION, String.Empty));
                break;

            case IM_Message.MESSAGE_TYPE_FORM_CLOSING:
                MessengerStructure.Remove(message);
                break;

            case IM_Message.MESSAGE_TYPE_BROADCAST:
                MessageBox.Show(message, "Broadcast From " + message.From, MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_CONNECTED:
                SetText(message + " connected.");
                MessageWindowRouter(message);
                ClientConnected((string)message);
                break;

            case IM_Message.MESSAGE_TYPE_CLIENT_DISCONNECTED:
                SetText(message + " disconnected.");
                MessageWindowRouter(message);
                ClientDisconnected((string)message);
                break;

            case IM_Message.MESSAGE_TYPE_SERVER_DISCONNECTING:
                //ShuttingDown();

                SetText("Server disconnecting.");
                SetStatus("Server Disconnected");
                clientsListBox.Items.Clear();
                EnableDisableControls(true);
                break;
            }
        }