Advertisement
Guest User

Untitled

a guest
May 21st, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Net.Sockets;
  11. using System.Net;
  12.  
  13. namespace WindowsFormsApp1
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         bool alive = false; // будет ли работать поток для приема
  18.         UdpClient client;
  19.         const int LOCALPORT = 8001; // порт для приема сообщений
  20.         const int REMOTEPORT = 8001; // порт для отправки сообщений
  21.         const int TTL = 20;
  22.         const string HOST = "235.5.5.1"; // хост для групповой рассылки
  23.         IPAddress groupAddress; // адрес для групповой рассылки
  24.  
  25.         string userName; // имя пользователя в чате
  26.  
  27.         public Form1()
  28.         {
  29.             InitializeComponent();
  30.  
  31.             logoutButton.Enabled = false;
  32.             sendButton.Enabled = false;
  33.  
  34.             groupAddress = IPAddress.Parse(HOST);
  35.         }
  36.  
  37.         private void loginButton_Click(object sender, EventArgs e)
  38.         {
  39.  
  40.             userName = userNameTextBox.Text;
  41.             userNameTextBox.ReadOnly = true;
  42.  
  43.             try
  44.             {
  45.                 client = new UdpClient(LOCALPORT);
  46.                 // присоединяемся к групповой рассылке
  47.                 client.JoinMulticastGroup(groupAddress, TTL);
  48.  
  49.                 // запускаем задачу на прием сообщений
  50.                 Task receiveTask = new Task(ReceiveMessages);
  51.                 receiveTask.Start();
  52.  
  53.                 // отправляем первое сообщение о входе нового пользователя
  54.                 string message = userName + " вошел в чат";
  55.                 byte[] data = Encoding.UTF8.GetBytes(message);
  56.                 client.Send(data, data.Length, HOST, REMOTEPORT);
  57.  
  58.                 loginButton.Enabled = false;
  59.                 logoutButton.Enabled = true;
  60.                 sendButton.Enabled = true;
  61.             }
  62.             catch (Exception ex)
  63.             {
  64.                 MessageBox.Show(ex.Message);
  65.             }
  66.  
  67.         }
  68.  
  69.         // метод приема сообщений
  70.         private void ReceiveMessages()
  71.         {
  72.             alive = true;
  73.             try
  74.             {
  75.                 while (alive)
  76.                 {
  77.                     IPEndPoint remoteIp = null;
  78.                     byte[] data = client.Receive(ref remoteIp);
  79.                     string message = Encoding.UTF8.GetString(data);
  80.  
  81.                     // добавляем полученное сообщение в текстовое поле
  82.                     this.Invoke(new MethodInvoker(() =>
  83.                     {
  84.                         string time = DateTime.Now.ToShortTimeString();
  85.                         chatTextBox.Text = time + " " + message + "\r\n" + chatTextBox.Text;
  86.                     }));
  87.                 }
  88.             }
  89.             catch (ObjectDisposedException)
  90.             {
  91.                 if (!alive)
  92.                     return;
  93.                 throw;
  94.             }
  95.             catch (Exception ex)
  96.             {
  97.                 MessageBox.Show(ex.Message);
  98.             }
  99.         }
  100.  
  101.         // обработчик нажатия кнопки sendButton
  102.         private void sendButton_Click(object sender, EventArgs e)
  103.         {
  104.             try
  105.             {
  106.                 string message = String.Format("{0}: {1}", userName, messageTextBox.Text);
  107.                 byte[] data = Encoding.UTF8.GetBytes(message);
  108.                 client.Send(data, data.Length, HOST, REMOTEPORT);
  109.                 messageTextBox.Clear();
  110.             }
  111.             catch (Exception ex)
  112.             {
  113.                 MessageBox.Show(ex.Message);
  114.             }
  115.         }
  116.  
  117.         // обработчик нажатия кнопки logoutButton
  118.         private void logoutButton_Click(object sender, EventArgs e)
  119.         {
  120.             ExitChat();
  121.         }
  122.  
  123.         // выход из чата
  124.         private void ExitChat()
  125.         {
  126.             string message = userName + " покидает чат";
  127.             byte[] data = Encoding.UTF8.GetBytes(message);
  128.             client.Send(data, data.Length, HOST, REMOTEPORT);
  129.             client.DropMulticastGroup(groupAddress);
  130.  
  131.             alive = false;
  132.             client.Close();
  133.  
  134.             loginButton.Enabled = true;
  135.             logoutButton.Enabled = false;
  136.             sendButton.Enabled = false;
  137.         }
  138.  
  139.         // обработчик события закрытия формы
  140.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  141.         {
  142.             if (alive)
  143.                 ExitChat();
  144.         }
  145.     }
  146. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement