Exemple #1
0
        // this code runs when a message was received
        void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            switch (e.Topic.ToLower())
            {
            case "picture":
                BitmapImage bitimg = Utils.ByteToImage(e.Message);
                Dispatcher.Invoke(delegate {                  // we need this construction because the receiving code in the library and the UI with textbox run on different threads
                    ImageViewer2.Source   = bitimg;
                    btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                });
                break;

            case "bundle":
                DataInfo imageData = ExtendedSerializerExtensions.Deserialize <DataInfo>(e.Message);
                Dispatcher.Invoke(delegate {                  // we need this construction because the receiving code in the library and the UI with textbox run on different threads
                    ImageViewer2.Source   = Utils.ByteToImage(imageData.ImageData);
                    txtReceived.Text      = (string.IsNullOrEmpty(imageData.PublisherMessage) ? "": imageData.PublisherMessage + "\n") + imageData.FileName;
                    txtReceivedDate.Text  = imageData.SentDateTime.ToString();
                    btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                });
                break;

            default:
                string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
                Dispatcher.Invoke(delegate {                  // we need this construction because the receiving code in the library and the UI with textbox run on different threads
                    txtReceived.Text      = ReceivedMessage;
                    btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                });
                break;
            }
        }
        protected void RecieveFileList(TextView contentLabel, ListView contentListView)
        {
            contentListView.OpenSelectedItem -= current_mode;
            current_mode = (a) => RetrieveFile(a.Value.ToString());
            contentListView.OpenSelectedItem += current_mode;
            var endpoint = new IPEndPoint(IPAddress.Parse(SnailMailClient.ServerIp), SnailMailClient.ServerPort);
            var sock     = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            sock.Connect(endpoint);

            var ns = new NetworkStream(sock, true);

            ns.Write(BitConverter.GetBytes(0));
            //Checks for code sent by server to see if it has files it can recieve
            byte[] youHaveMail = new byte[4];

            ns.Read(youHaveMail, 0, 4);
            if (BitConverter.ToInt32(youHaveMail) == 1)
            {
                contentLabel.Text = "You have no waiting Messages";
                ns.Close();
            }
            else if (BitConverter.ToInt32(youHaveMail) == 0)
            {
                byte[] lengthOfData = new byte[4];
                ns.Read(lengthOfData, 0, 4);
                byte[] dataBytes = new byte[BitConverter.ToInt32(lengthOfData)];
                ns.Read(dataBytes, 0, dataBytes.Length);
                contentLabel.Text = "Select a file to download if it is ready";

                List <string> fileList = ExtendedSerializerExtensions.Deserialize <List <string> >(dataBytes);
                //contentLabel.Text = fileList[0];
                contentListView.SetSource(fileList);
                contentListView.CanFocus = true;
                contentListView.SetFocus();
                //sock.Close();
            }
        }
Exemple #3
0
        private async Task DoFS(Socket sock)
        {
            do
            {
                var clientSocket = await Task.Factory.FromAsync(
                    new Func <AsyncCallback, object, IAsyncResult>(sock.BeginAccept),
                    new Func <IAsyncResult, Socket>(sock.EndAccept), null).ConfigureAwait(false);

                Console.WriteLine("connected");

                using (var stream = new NetworkStream(clientSocket, true))
                {
                    byte[] modeBytes = new byte[4];
                    stream.Read(modeBytes, 0, modeBytes.Length);
                    int mode = BitConverter.ToInt32(modeBytes);

                    //Send file to client
                    if (mode == 2)
                    {
                        Console.WriteLine("Send file to client");

                        string path = "ServerFiles/" + clientSocket.RemoteEndPoint.ToString().Split(':')[0] + "/";
                        //Dictionary<string, string> fileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(path + "Manager.json")); ;

                        byte[] packLength = new byte[4];

                        stream.Read(packLength, 0, 4);
                        byte[] keyBytes = new byte[BitConverter.ToInt32(packLength)];
                        stream.Read(keyBytes, 0, keyBytes.Length);

                        string key = Encoding.UTF8.GetString(keyBytes);
                        Console.WriteLine(key);
                        byte[] fileData = File.ReadAllBytes(path + key + ".dat");

                        /*var memstream = new MemoryStream();
                         * memstream.Write(fileData);
                         * memstream.Position = 0;*/
                        //FileEncoding.FileStructure fs = FileEncoding.FileStructureRetriever(memstream);
                        //Console.WriteLine(fs.fileName);

                        stream.Write(fileData);
                    }
                    //Send list of files and times until able to be recieved
                    else if (mode == 0)
                    {
                        string path = "ServerFiles/" + clientSocket.RemoteEndPoint.ToString().Split(':')[0] + "/";
                        //Console.WriteLine(File.Exists(path+"Manager.json"));
                        Dictionary <string, string> fileList = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(path + "Manager.json"));;
                        List <string> fileNames = new List <string>();

                        try
                        {
                            fileList = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(path + "Manager.json"));
                        }
                        catch
                        {
                            stream.Write(BitConverter.GetBytes(1));
                            clientSocket.Close();
                        }
                        stream.Write(BitConverter.GetBytes(0));
                        foreach (KeyValuePair <string, string> entry in fileList)
                        {
                            DateTime endTime = DateTime.Parse(entry.Value).AddDays(SnailMailServer.days_delayed);
                            TimeSpan ts      = endTime.Subtract(DateTime.UtcNow);
                            if (ts.CompareTo(TimeSpan.Zero) > 0)
                            {
                                fileNames.Add(entry.Key + " - " + ts.ToString(@"dd\:hh\:mm\:ss"));
                            }
                            else
                            {
                                ts = new TimeSpan(0, 0, 0, 0);
                                fileNames.Add(entry.Key + " - " + ts.ToString(@"dd\:hh\:mm\:ss"));
                            }
                        }

                        /*foreach(string s in fileNames)
                         * {
                         *  Console.WriteLine(s);
                         * }*/

                        byte[] dataToSend = ExtendedSerializerExtensions.Serialize(fileNames);
                        //List<string> yeetus = (List<string>)binForm.Deserialize(memStream);

                        //Console.WriteLine(yeetus[0]);
                        List <byte> fullLoad = new List <byte>();
                        fullLoad.AddRange(BitConverter.GetBytes(dataToSend.Length));
                        fullLoad.AddRange(dataToSend);
                        List <string> yeetus = ExtendedSerializerExtensions.Deserialize <List <string> >(dataToSend);
                        Console.WriteLine(yeetus[0]);
                        stream.Write(fullLoad.ToArray());
                    }
                    //Recieve file from client
                    else if (mode == 1)
                    {
                        FileEncoding.FileStructure fs = FileEncoding.FileStructureRetriever(stream);
                        byte[] bytes = FileEncoding.StreamPrepper(fs);
                        Dictionary <string, string> fileList;
                        string path = "ServerFiles/" + fs.ipSender.ToString() + "/";

                        if (!Directory.Exists("ServerFiles/" + fs.ipSender.ToString() + "/"))
                        {
                            Directory.CreateDirectory(path);
                            FileStream stream1 = File.Create(path + "Manager.json");
                            stream1.Write(Encoding.UTF8.GetBytes("{}"));
                            stream1.Close();
                        }
                        try
                        {
                            fileList = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(path + "Manager.json"));
                        }
                        catch
                        {
                            fileList = new Dictionary <string, string>();
                        }
                        FileStream fstream = File.Create(path + fs.fileName + ".dat");
                        if (!fileList.TryGetValue(fs.fileName, out _))
                        {
                            fileList.Add(fs.fileName, fs.dateSent);
                        }
                        else
                        {
                            fileList[fs.fileName] = fs.dateSent;
                        }

                        File.WriteAllText(path + "Manager.json", JsonConvert.SerializeObject(fileList, Formatting.Indented));
                        fstream.Write(bytes);
                        fstream.Close();
                        Console.WriteLine(fs.ipSender.ToString());
                        clientSocket.Close();
                    }
                }
            } while (true);
        }
Exemple #4
0
        public MainWindow()
        {
            InitializeComponent();

            //"127.0.0.1" or "localhost" when you installed Mosquitto Broker in your local machine.
            //"test.mosquitto.org";
            //string BrokerAddress = "192.168.3.5";
            string BrokerAddress = "localhost";
            int    BrokerPort    = 1883;

            // use a unique id as client id, each time we start the application
            clientId = Guid.NewGuid().ToString();

            string username = "******";
            string password = "******";

            // Create a new MQTT client.
            var factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            //// Certificate based authentication
            //List<X509Certificate> certs = new List<X509Certificate>
            //{
            //    new X509Certificate2("certificate1.pfx")
            //};

            // Create TCP based options using the builder.
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientId)
                          .WithTcpServer(BrokerAddress, BrokerPort)
                          .WithCredentials(username, password) //("bud", "%spencer%")
                                                               //.WithTls(new MqttClientOptionsBuilderTlsParameters
                                                               //{
                                                               //    UseTls = true,
                                                               //    Certificates = certs,
                                                               //    CertificateValidationHandler = (MqttClientCertificateValidationCallbackContext context) =>
                                                               //    {
                                                               //        // TODO: Check conditions of certificate by using above parameters.
                                                               //        return true;
                                                               //    }
                                                               //})
                                                               //.WithTls()
                          .WithCleanSession()
                          .Build();

            // Subscribing to a topic
            mqttClient.UseConnectedHandler(async e =>
            {
                await UseConnectedMessage();

                //Console.WriteLine("### CONNECTED WITH SERVER ###");

                //// Subscribe to a topic
                //await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build());

                //Console.WriteLine("### SUBSCRIBED ###");
            });

            // Reconnecting
            mqttClient.UseDisconnectedHandler(async e =>
            {
                Dispatcher.Invoke(delegate
                {
                    sbMessage.Text = "Disconnected from MQTT Brokers.";
                });
                //Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
                }
                catch
                {
                    //Console.WriteLine("### RECONNECTING FAILED ###");
                }
            });

            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;

                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        ////Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                        //Dispatcher.Invoke(delegate
                        //{
                        //    // we need this construction because the receiving code in the library and the UI with textbox run on different threads
                        //    txtReceived.Text = payload;
                        //    btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        //});
                        switch (topic.ToLower())
                        {
                        case "picture":
                            BitmapImage bitimg = Utils.ByteToImage(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                ImageViewer2.Source   = bitimg;
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;

                        case "bundle":
                            DataInfo imageData = ExtendedSerializerExtensions.Deserialize <DataInfo>(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                ImageViewer2.Source   = Utils.ByteToImage(imageData.ImageData);
                                txtReceived.Text      = (string.IsNullOrEmpty(imageData.PublisherMessage) ? "" : imageData.PublisherMessage + "\n") + imageData.FileName;
                                txtReceivedDate.Text  = imageData.SentDateTime.ToString();
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;

                        default:
                            string ReceivedMessage = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                txtReceived.Text      = ReceivedMessage;
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;
                        }
                    }

                    //string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });

            //mqttClient.ConnectAsync(options, CancellationToken.None).Wait(CancellationToken.None);
            mqttClient.ConnectAsync(options).GetAwaiter().GetResult();
        }