private void MenuItemFind_Click(object sender, RoutedEventArgs e) { try { StopGameOnline(); tcpClientOpponent = new TcpClient(); tcpClientOpponent.Connect(GameIPConfig.ServerIPAddress, GameIPConfig.Port); byte[] data = new byte[256]; NetworkStream stream = tcpClientOpponent.GetStream(); int bytes; MenuItemsToggle(false); // open waitwindow to wait opponent WaitWindow waitWindow = new WaitWindow() { Owner = this, Message = "Searching for an opponent" }; bool cancelation = true; Task.Run(() => { try { do { bytes = stream.Read(data, 0, data.Length); if (bytes == 1 && data[0] == readyPacket) { this.Dispatcher.Invoke(() => { cancelation = false; waitWindow.Close(); playingOnServer = true; connectionSuccessful(); }); } } while (stream.DataAvailable); } catch (Exception ex) { } }); waitWindow.Closing += (sendr, ev) => { if (cancelation) { tcpClientOpponent.Close(); MenuItemsToggle(true); } }; waitWindow.ShowDialog(); } catch (Exception ex) { MessageBox.Show(this, ex.ToString()); } }
void waitForConnect() { try { TcpListener server = new TcpListener(IPAddress.Any, GameIPConfig.Port); server.Start(); WaitWindow waitWindow = new WaitWindow() { Owner = this, Message = "Waiting for connection on port " + GameIPConfig.Port }; Thread task = new Thread(() => { while (tcpClientOpponent == null) { // Console.WriteLine("Ожидание подключений... "); try { tcpClientOpponent = server.AcceptTcpClient(); } catch (Exception ex) { break; } // Console.WriteLine("Подключен клиент. Выполнение запроса..."); this.Dispatcher.Invoke(() => { waitWindow.Close(); connectionSuccessful(); }); } }); task.Start(); waitWindow.Closing += (sender, e) => { server.Stop(); }; waitWindow.ShowDialog(); } catch (Exception ex) { MessageBox.Show(this, ex.ToString()); } }