Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- namespace ChatTCP_WPF
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- static string userName = "Default";
- private const string HOST = "127.0.0.1";
- private const int PORT = 12000;
- static TcpClient client;
- static NetworkStream stream;
- public MainWindow()
- {
- InitializeComponent();
- }
- // получение сообщений
- void receiveMessage()
- {
- while (true)
- {
- try
- {
- byte[] data = new byte[64]; // буфер для получаемых данных
- StringBuilder builder = new StringBuilder();
- int bytes = 0;
- do
- {
- bytes = stream.Read(data, 0, data.Length);
- builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
- }
- while (stream.DataAvailable);
- string message = builder.ToString();
- textBoxChat.Dispatcher.Invoke(new Action<string>((s) => textBoxChat.AppendText(s)), message);//вывод сообщения
- }
- catch
- {
- textBoxChat.Dispatcher.Invoke(new Action<string>((s) => textBoxChat.AppendText(s)), "Подключение прервано!");
- disconnect();
- }
- }
- }
- void disconnect()
- {
- if (stream != null)
- stream.Close();//отключение потока
- if (client != null)
- client.Close();//отключение клиента
- Environment.Exit(0); //завершение процесса
- }
- private void buttonSend_Click(object sender, RoutedEventArgs e)
- {
- string message = textBoxMess.Text;
- byte[] data = Encoding.Unicode.GetBytes(message);
- stream.Write(data, 0, data.Length);
- textBoxMess.Clear();
- }
- private void button_Click(object sender, RoutedEventArgs e)
- {
- client = new TcpClient();
- try
- {
- client.Connect(HOST, PORT); //подключение клиента
- stream = client.GetStream(); // получаем поток
- string message = userName;
- byte[] data = Encoding.Unicode.GetBytes(message);
- stream.Write(data, 0, data.Length);
- // запускаем новый поток для получения данных
- Thread receiveThread = new Thread(new ThreadStart(receiveMessage));
- receiveThread.Start(); //старт потока прослушивания входящих сообщений
- textBoxChat.AppendText("Добро пожаловать, " + userName);
- }
- catch (Exception ex)
- {
- textBoxChat.AppendText(ex.Message);
- }
- finally
- {
- disconnect();
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment