Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- 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.Threading;
- using System.Net.Sockets;
- namespace client
- {
- /// <summary>
- /// Логика взаимодействия для MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
- private const string host = "127.0.0.1";
- private const int port = 8888;
- static TcpClient client;
- static NetworkStream stream;
- // получение сообщений
- public void ReceiveMessage()
- {
- //var outer = Task.Factory.StartNew(() =>
- //{
- 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));
- string message1 = builder.ToString();
- Dispatcher.BeginInvoke(new Action(
- () => lb.Items.Add(message1)));
- // }
- // while (stream.DataAvailable);
- }
- catch
- {
- Dispatcher.BeginInvoke(new Action(
- () => lb.Items.Add("Подключение прервано!")));
- //соединение было прервано
- Disconnect();
- }
- // }
- //});//outer.Wait();
- }
- public void Disconnect()
- {
- if (stream != null)
- stream.Close();//отключение потока
- if (client != null)
- client.Close();//отключение клиента
- // Environment.Exit(0); //завершение процесса
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- string Name = tb1.Text;
- string Password = tb3.Text;
- string userName = Name + ":" + Password;
- client = new TcpClient();
- try
- {
- client.Connect(host, port); //подключение клиента
- stream = client.GetStream(); // получаем поток
- byte[] data = Encoding.Unicode.GetBytes(Name + ":" + Password);
- stream.Write(data, 0, data.Length);
- }
- catch (Exception ex)
- {
- Dispatcher.BeginInvoke(new Action(
- () => lb.Items.Add(ex.Message)));
- }
- Thread receiveThread = new Thread(ReceiveMessage);
- receiveThread.Start();
- // finally
- // {
- // Disconnect();
- // }
- }
- private void Button_Click_1(object sender, RoutedEventArgs e)
- {
- string message = tb2.Text;
- Dispatcher.BeginInvoke(new Action(
- () => lb.Items.Add("Вы: " + message)));
- byte[] data = Encoding.Unicode.GetBytes(message);
- stream.Write(data, 0, data.Length);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement