IT rekvalifikace s garancí práce. Seniorní programátoři vydělávají až 160 000 Kč/měsíc a rekvalifikace je prvním krokem. Zjisti, jak na to!
Hledáme nové posily do ITnetwork týmu. Podívej se na volné pozice a přidej se do nejagilnější firmy na trhu - Více informací.

UDP client/server

WPF app client/server messenger

C# .NET

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Messenger
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer timer;
        Random random;
        Socket socketSend;
        Socket socketReceive;
        Thread connecting_Holding_Thread;
        Thread first_Connection_Thread;
        byte[] consequential_Data;
        byte[] random_Message;
        string destination_IP_Address;
        string connecting_Holding_Message;
        int connecting_Holding_Message_Size;
        int destination_Port;
        int connected_Time;
        int connected_Time_Max;

        public MainWindow()
        {
            InitializeComponent();

            connected_Time_Max = 45;
            connecting_Holding_Message_Size = 256;
            
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 1);

            textBox_Text_Message.IsEnabled = false;
            button_Send.IsEnabled = false;
            button_Disconnect.Visibility = Visibility.Hidden;
            button_Disconnect.IsEnabled = false;
        }

        private void button_Connect_Click(object sender, RoutedEventArgs e)
        {
            button_Connect.Visibility = Visibility.Hidden;
            button_Connect.IsEnabled = false;
            button_Disconnect.Visibility = Visibility.Visible;
            button_Disconnect.IsEnabled = true;

            destination_IP_Address = textBox_IP_Address.Text.ToString();
            destination_Port = Int32.Parse(textBox_Port.Text.ToString());

            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socketSend.EnableBroadcast = true;
            socketSend.Connect(new IPEndPoint(IPAddress.Parse(destination_IP_Address), destination_Port));

            textBox_IP_Address.IsEnabled = false;
            textBox_Port.IsEnabled = false;

            first_Connection_Thread = new Thread(new ThreadStart(first_Connection));
            first_Connection_Thread.IsBackground = true;
            connecting_Holding_Thread = new Thread(new ThreadStart(connecting_Holding));
            connecting_Holding_Thread.IsBackground = true;

            textBox_Chat.Text = "Connecting";
            first_Connection_Thread.Start();
        }

        private void button_Disconnect_Click(object sender, RoutedEventArgs e)
        {
            button_Connect.Visibility = Visibility.Visible;
            button_Connect.IsEnabled = true;
            button_Disconnect.Visibility = Visibility.Hidden;
            button_Disconnect.IsEnabled = false;

            textBox_IP_Address.IsEnabled = true;
            textBox_Port.IsEnabled = true;
            textBox_Text_Message.IsEnabled = false;
            button_Send.IsEnabled = false;

            textBox_Chat.Text = "Disconnected";

            socketReceive.Close();
            socketSend.Close();

            first_Connection_Thread.Abort();
            connecting_Holding_Thread.Abort();
        }

        private void send_message(Boolean is_Connecting_Holding, Boolean is_Checksum, int number_Of_Socket, int count_Of_Socket, byte[] data)
        {
            byte[] help_variable = header_Create(is_Connecting_Holding, is_Checksum, number_Of_Socket, count_Of_Socket);

            consequential_Data = new byte[help_variable.Length + data.Length];
            help_variable.CopyTo(consequential_Data, 0);
            data.CopyTo(consequential_Data, help_variable.Length);

            socketSend.Send(consequential_Data);
        }

        private byte[] header_Create(Boolean is_Connecting_Holding, Boolean is_Checksum, int number_Of_Socket, int count_Of_Socket)
        {
            consequential_Data = new byte[10];
            consequential_Data[0] = is_Connecting_Holding ? (byte)1 : (byte)0;
            consequential_Data[1] = is_Checksum ? (byte)1 : (byte)0;
            BitConverter.GetBytes(number_Of_Socket).CopyTo(consequential_Data, 2);
            BitConverter.GetBytes(count_Of_Socket).CopyTo(consequential_Data, 6);

            return consequential_Data;
        }

        private byte[] header_Remove(byte[] socket)
        {
            consequential_Data = new byte[socket.Length - 10];
            Array.Copy(socket, 10, consequential_Data, 0, socket.Length - 10);
            return consequential_Data;
        }

        private void first_Connection()
        {
            connected_Time = 0;
            timer.Start();
            socketReceive = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socketReceive.EnableBroadcast = true;
            socketReceive.Bind(new IPEndPoint(IPAddress.Parse(destination_IP_Address), destination_Port));
            random_Message = GenerateRandomMessage();

            send_message(true, false, 0, 0, random_Message);
            while (connected_Time < connected_Time_Max)
            {
                if (socketReceive.Available > 0)
                {
                    byte[] socket = new byte[socketReceive.Available];
                    socketReceive.Receive(socket, SocketFlags.None);

                    if (header_Remove(socket).SequenceEqual(random_Message))
                    {
                        Dispatcher.Invoke(() => {
                            textBox_Chat.Text = "Connecting successful" + Environment.NewLine;
                            textBox_Text_Message.IsEnabled = true;
                            button_Send.IsEnabled = true;
                        });
                        timer.Stop();
                        connecting_Holding_Thread.Start();
                        first_Connection_Thread.Abort();
                    }
                    else
                        Dispatcher.Invoke(() => {
                            textBox_Chat.Text += ".";
                        });

                    random_Message = GenerateRandomMessage();
                    send_message(true, false, 0, 0, random_Message);
                }
                else
                    Dispatcher.Invoke(() => {
                        textBox_Chat.Text += " .";
                    });

                Thread.Sleep(1000);
            }

            Dispatcher.Invoke(() => {
                textBox_Chat.Text = "Connection unsuccessfully" + Environment.NewLine;
            });

            timer.Stop();
        }

        protected void connecting_Holding()
        {
            connected_Time = 0;
            Dispatcher.Invoke(() => {
                textBox_IP_Address.IsEnabled = false;
                textBox_Port.IsEnabled = false;
            });
            timer.Start();

            random_Message = GenerateRandomMessage();
            send_message(true, false, 0, 0, random_Message);
            while (connected_Time < connected_Time_Max)
            {
                if (socketReceive.Available > 0)
                {
                    byte[] socket = new byte[socketReceive.Available];
                    socketReceive.Receive(socket, SocketFlags.None);

                    if (header_Remove(socket).SequenceEqual(random_Message))
                        connected_Time = 0;

                    Thread.Sleep(1000);
                    random_Message = GenerateRandomMessage();
                    send_message(true, false, 0, 0, random_Message);
                }
            }
            
            Dispatcher.Invoke(() => {
                textBox_Chat.Text += "Connection lost." + Environment.NewLine;
            });

            timer.Stop();
            connecting_Holding_Thread.Abort();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            connected_Time++;
        }

        private byte[] GenerateRandomMessage()
        {
            random = new Random();
            connecting_Holding_Message = string.Empty;

            for (int i = 0; i < connecting_Holding_Message_Size; i++)
                connecting_Holding_Message += ((char)random.Next(97, 122)).ToString();

            return Encoding.Convert(Encoding.Unicode, Encoding.UTF8, Encoding.Unicode.GetBytes(connecting_Holding_Message));
        }
    }
}

Neformátovaný

Přidáno: 12.10.2016
Expirace: Neuvedeno

Aktivity