Guest User

Untitled

a guest
Nov 17th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 3.49 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9.  
  10. namespace ChatTCP_WPF
  11. {
  12.     /// <summary>
  13.     /// Interaction logic for MainWindow.xaml
  14.     /// </summary>
  15.     public partial class MainWindow : Window
  16.     {
  17.         static string userName = "Default";
  18.         private const string HOST = "127.0.0.1";
  19.         private const int PORT = 12000;
  20.         static TcpClient client;
  21.         static NetworkStream stream;
  22.         public MainWindow()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.         // получение сообщений
  27.         void receiveMessage()
  28.         {
  29.             while (true)
  30.             {
  31.                 try
  32.                 {
  33.                     byte[] data = new byte[64]; // буфер для получаемых данных
  34.                     StringBuilder builder = new StringBuilder();
  35.                     int bytes = 0;
  36.                     do
  37.                     {
  38.                         bytes = stream.Read(data, 0, data.Length);
  39.                         builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
  40.                     }
  41.                     while (stream.DataAvailable);
  42.  
  43.                     string message = builder.ToString();
  44.  
  45.                     textBoxChat.Dispatcher.Invoke(new Action<string>((s) => textBoxChat.AppendText(s)), message);//вывод сообщения
  46.                 }
  47.                 catch
  48.                 {
  49.                     textBoxChat.Dispatcher.Invoke(new Action<string>((s) => textBoxChat.AppendText(s)), "Подключение прервано!");
  50.                     disconnect();
  51.                 }
  52.             }
  53.         }
  54.  
  55.         void disconnect()
  56.         {
  57.             if (stream != null)
  58.                 stream.Close();//отключение потока
  59.             if (client != null)
  60.                 client.Close();//отключение клиента
  61.             Environment.Exit(0); //завершение процесса
  62.         }
  63.  
  64.         private void buttonSend_Click(object sender, RoutedEventArgs e)
  65.         {
  66.             string message = textBoxMess.Text;
  67.             byte[] data = Encoding.Unicode.GetBytes(message);
  68.             stream.Write(data, 0, data.Length);
  69.             textBoxMess.Clear();
  70.         }
  71.  
  72.         private void button_Click(object sender, RoutedEventArgs e)
  73.         {
  74.  
  75.             client = new TcpClient();
  76.             try
  77.             {
  78.                 client.Connect(HOST, PORT); //подключение клиента
  79.                 stream = client.GetStream(); // получаем поток
  80.                
  81.  
  82.                 string message = userName;
  83.                 byte[] data = Encoding.Unicode.GetBytes(message);
  84.                 stream.Write(data, 0, data.Length);
  85.  
  86.                 // запускаем новый поток для получения данных
  87.                 Thread receiveThread = new Thread(new ThreadStart(receiveMessage));
  88.                 receiveThread.Start(); //старт потока прослушивания входящих сообщений
  89.                 textBoxChat.AppendText("Добро пожаловать, " + userName);
  90.             }
  91.             catch (Exception ex)
  92.             {
  93.                 textBoxChat.AppendText(ex.Message);
  94.             }
  95.             finally
  96.             {
  97.                 disconnect();
  98.             }
  99.         }
  100.     }
  101. }
Add Comment
Please, Sign In to add comment